148. Sort List #
Problem #
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
Summary #
Sort a linked list, requiring the time complexity to be O(n log n) and the space complexity to be O(1)
Solution Approach #
This problem can only use merge sort to meet the requirements. The 2 operations needed for merge sort have already appeared in other problems: finding the middle point is Problem 876, and merging 2 sorted linked lists is Problem 21.
Code #
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func sortList(head *ListNode) *ListNode {
length := 0
cur := head
for cur != nil {
length++
cur = cur.Next
}
if length <= 1 {
return head
}
middleNode := middleNode(head)
cur = middleNode.Next
middleNode.Next = nil
middleNode = cur
left := sortList(head)
right := sortList(middleNode)
return mergeTwoLists(left, right)
}
func middleNode(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
p1 := head
p2 := head
for p2.Next != nil && p2.Next.Next != nil {
p1 = p1.Next
p2 = p2.Next.Next
}
return p1
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists(l1, l2.Next)
return l2
}