func cut(head *ListNode, n int) *ListNode {
p := head
for n--; n > 0 && p != nil; n-- {
p = p.Next
}
if p == nil {
return nil
}
next := p.Next
p.Next = nil
return next
}
func sortList(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
length := 0
for p := head; p != nil; p = p.Next {
length++
}
for i := 1; i < length; i *= 2 {
for cur, pre := dummy.Next, dummy; cur != nil; {
left := cur
right := cut(left, i)
cur = cut(right, i)
pre.Next = mergeTwoLists(left, right)
for pre.Next != nil {
pre = pre.Next
}
}
}
return dummy.Next
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
dummy := &ListNode{}
cur := dummy
for l1 != nil && l2 != nil {
if l1.Val <= l2.Val {
cur.Next = l1
l1 = l1.Next
} else {
cur.Next = l2
l2 = l2.Next
}
cur = cur.Next
}
if l1 == nil {
cur.Next = l2
} else {
cur.Next = l1
}
return dummy.Next
}