-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148_sortList.py
55 lines (43 loc) · 1.21 KB
/
148_sortList.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
# 148. Sort List
# Merge Sort
# Neetcode: https://www.youtube.com/watch?v=TGveA1oFhrc
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def merge(left,right):
tail = dummy = ListNode()
while left and right:
if left.val<=right.val:
tail.next = left
left = left.next
else:
tail.next = right
right = right.next
tail = tail.next
if left:
tail.next = left
if right:
tail.next = right
return dummy.next
def getMid(head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
# split the list into 2 halves
left = head
right = getMid(head)
temp = right.next
right.next = None
right = temp
left = self.sortList(left)
right = self.sortList(right)
return merge(left,right)