-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0148-sort-list.py
More file actions
58 lines (48 loc) · 1.53 KB
/
0148-sort-list.py
File metadata and controls
58 lines (48 loc) · 1.53 KB
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
# time complexity: O(nlogn)
# space complexity: O(logn)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
mid = self.getMid(head)
left = self.sortList(head)
right = self.sortList(mid)
return self.merge(left, right)
def merge(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
curr = dummy
while list1 and list2:
if list1.val < list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next
curr = curr.next
curr.next = list1 if list1 else list2
return dummy.next
def getMid(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = None
fast = head
while fast and fast.next:
slow = fast if not slow else slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
return mid
def printLinkedList(head):
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
root = ListNode(4)
root.next = ListNode(2)
root.next.next = ListNode(1)
root.next.next.next = ListNode(3)
printLinkedList(Solution().sortList(root))