148. 排序链表

This commit is contained in:
2026-08-13 20:57:24 +08:00
parent 4ee6823943
commit f19f1f5e85
2 changed files with 76 additions and 65 deletions
+49 -65
View File
@@ -1,78 +1,62 @@
package main
import "fmt"
/**
* Definition for singly-linked list.*/
type ListNode struct {
Val int
Next *ListNode
}
func makeLink(arr []int) *ListNode {
if len(arr) == 0 {
return nil
}
head := &ListNode{}
cur := head
for _, v := range arr {
cur.Next = &ListNode{Val: v}
cur = cur.Next
}
return head.Next
}
func checkLink(head *ListNode) {
for head != nil {
fmt.Println(head.Val)
head = head.Next
}
}
func reverseBetween(head *ListNode, left int, right int) *ListNode {
if head.Next == nil {
func conquerAndSort(head *ListNode, end *ListNode) *ListNode {
if head == nil || head == end || head.Next == nil {
return head
}
left--
right--
cur_idx := 0
cur := head
var left_node *ListNode
var left_pre_node *ListNode = nil
_ = left_pre_node
var last_node *ListNode = nil
do_rev := false
for {
if cur_idx == left {
left_node = cur
left_pre_node = last_node
do_rev = true
}
next := cur.Next
if do_rev {
next = cur.Next
cur.Next = last_node
if cur_idx == right {
left_node.Next = next
if left_pre_node != nil {
left_pre_node.Next = cur
} else {
head = cur
}
do_rev = false
if head.Next == end {
if end != nil {
if head.Val > end.Val {
head.Val, end.Val = end.Val, head.Val
}
}
last_node = cur
cur = next
cur_idx++
if cur == nil {
break
return head
}
if head.Next.Next == end {
if head.Val > head.Next.Val {
head.Next.Val, head.Val = head.Val, head.Next.Val
}
return head
}
slow, fast := head, head
for fast.Next != nil && fast.Next.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
lastSlow := slow
slow = slow.Next
lastSlow.Next = nil
a := conquerAndSort(head, nil)
b := conquerAndSort(slow, end)
if a.Val > b.Val {
a, b = b, a
}
// a Val < b Val
head = a
cur := a
a = a.Next
for a != nil && b != nil {
if a.Val > b.Val {
cur.Next = b
b = b.Next
} else {
cur.Next = a
a = a.Next
}
cur = cur.Next
}
if a == nil {
cur.Next = b
} else {
cur.Next = a
}
return head
}
func sortList(head *ListNode) *ListNode {
return conquerAndSort(head, nil)
}
func main() {
arr := []int{3, 5}
checkLink(reverseBetween(makeLink(arr), 1, 2))
arr := []int{-1, 5, 3, 4, 0}
checkLink(sortList(makeLink(arr)))
}