-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsort-list.py
70 lines (44 loc) · 1.55 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
70
"""
https://leetcode.com/submissions/detail/369690505/
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def merge(self, node1, node2):
temp_node = temp_node_head = ListNode(0)
while node1 and node2:
if node1.val < node2.val:
temp_node_head.next = node1
node1 = node1.next
else:
temp_node_head.next = node2
node2 = node2.next
temp_node_head = temp_node_head.next
temp_node_head.next = node1 or node2
temp_node = temp_node.next
return temp_node
def sortList(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
slow = head
fast = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
node_list_2_head = slow.next
slow.next = None
left = self.sortList(head)
right = self.sortList(node_list_2_head)
return self.merge(left, right)