题目:
题解:
func merge(head1, head2 *ListNode) *ListNode {dummyHead := &ListNode{}temp, temp1, temp2 := dummyHead, head1, head2for temp1 != nil && temp2 != nil {if temp1.Val <= temp2.Val {temp.Next = temp1temp1 = temp1.Next} else {temp.Next = temp2temp2 = temp2.Next}temp = temp.Next}if temp1 != nil {temp.Next = temp1} else if temp2 != nil {temp.Next = temp2}return dummyHead.Next
}func sortList(head *ListNode) *ListNode {if head == nil {return head}length := 0for node := head; node != nil; node = node.Next {length++}dummyHead := &ListNode{Next: head}for subLength := 1; subLength < length; subLength <<= 1 {prev, cur := dummyHead, dummyHead.Nextfor cur != nil {head1 := curfor i := 1; i < subLength && cur.Next != nil; i++ {cur = cur.Next}head2 := cur.Nextcur.Next = nilcur = head2for i := 1; i < subLength && cur != nil && cur.Next != nil; i++ {cur = cur.Next}var next *ListNodeif cur != nil {next = cur.Nextcur.Next = nil}prev.Next = merge(head1, head2)for prev.Next != nil {prev = prev.Next}cur = next}}return dummyHead.Next
}