funcquickSort(head, end *ListNode) { if head != end { node := sortPart(head, end) quickSort(head, node) quickSort(node.Next, end) } }
funcsortPart(head, end *ListNode) *ListNode { l, r := head, head.Next for r != end { if r.Val < head.Val { l = l.Next temp := l.Val l.Val = r.Val r.Val = temp } r = r.Next }
if l != head { temp := l.Val l.Val = head.Val head.Val = temp } return l }
newHead := &ListNode{Next: head} for subLen := 1; subLen < length; subLen *= 2 { prev, cur := newHead, newHead.Next for cur != nil { head1 := cur //subLen < length cur 不可能为nil for i := 1; i < subLen && cur.Next != nil; i++ { cur = cur.Next }
head2 := cur.Next cur.Next = nil cur = head2 //注意这里cur可能为nil for i := 1; i < subLen && cur != nil && cur.Next != nil; i++ { cur = cur.Next }
// 合并之前,如果head2尾后还有,这里必须断开 var next *ListNode if cur != nil { next = cur.Next cur.Next = nil }
prev.Next = merge(head1, head2) for prev.Next != nil { prev = prev.Next } cur = next } } return newHead.Next }