# Sort List

## # Definition for Singly-Linked List

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
1
2
3
4

## # Solution

### # Merge Sort

#### # Recursive Top Down

complexity

time: $O(n \log n)$
space: $O(\log n)$

def sortList(self, head: ListNode) -> ListNode:
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# disconnect
slow.next = None
return self.merge(left, right)

def merge(self, left, right):
if not left or not right:
return left or right
dummy = curr = ListNode(0)
while left and right:
if left.val < right.val:
curr.next = left
left = left.next
else:
curr.next = right
right = right.next
curr = curr.next
curr.next = left or right
return dummy.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

### # Iterative Bottom Up

Gradually increase sub_len to merge iteratively.

def sortList(self, head: ListNode) -> ListNode:

dummy = ListNode(0)
curr = dummy

else:
curr = curr.next
return dummy.next

length = 0
while node:
length += 1
node = node.next

sub_len = 1
while sub_len < length:
prev, curr = dummy, dummy.next
while curr:
for i in range(1, sub_len):
if curr and curr.next:
curr = curr.next
else:
break
curr.next = None
for i in range(1, sub_len):
if curr and curr.next:
curr = curr.next
else:
break

succ = None
if curr:
# split
succ = curr.next
curr.next = None

prev.next = merged
while prev.next:
prev = prev.next
curr = succ
sub_len <<= 1

return dummy.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60