-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsort-list.py
69 lines (51 loc) · 1.78 KB
/
sort-list.py
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
61
62
63
64
65
66
67
68
69
from typing import Optional, Tuple
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def merge(start, left, right, length: int):
new_head, new_tail = None, None
ptr_left, ptr_right = left, right
while ptr_left or ptr_right:
if ptr_left and (
(not ptr_right) or (ptr_right and ptr_left.val < ptr_right.val)
):
start.next, start, ptr_left = ptr_left, ptr_left, ptr_left.next
else:
start.next, start, ptr_right = ptr_right, ptr_right, ptr_right.next
return start
def cut_sublist_from_here(node: ListNode, nodes: int) -> ListNode:
for _ in range(nodes - 1):
if node:
node = node.next
node_next = node.next if node else None
if node:
node.next = None
return node_next
total = 0
node = head
while node:
total += 1
node = node.next
power = 0
cur_head = head
while (length := 2 ** power) < total:
node, cur_head = cur_head, None
start = ListNode()
prev = start
while node:
left = node
right = cut_sublist_from_here(left, length)
node = cut_sublist_from_here(right, length)
prev = merge(prev, left, right, length)
cur_head = start.next
power += 1
return cur_head
node = ListNode(4)
node.next = ListNode(2)
node.next.next = ListNode(1)
node.next.next.next = ListNode(3)
sol = Solution()
sol.sortList(node)