Here is the implementation:
function sortList(head):
if head == null or head.next == null:
return head
// Find middle with slow/fast
slow = head, fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
// Split
mid = slow.next
slow.next = null
// Recurse and merge
left = sortList(head)
right = sortList(mid)
return merge(left, right)
function merge(l1, l2):
dummy = new ListNode()
curr = dummy
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
time, stack space.