forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148.sort-list.py
62 lines (47 loc) · 1.46 KB
/
148.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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.merge_sort(head)
def merge_sort(self, head):
if head is None or head.next is None:
return head
#find middle
quick = head.next
slow = head
while (quick is not None and quick.next is not None):
quick = quick.next.next
slow = slow.next
left = head
right = slow.next
slow.next = None
#sort left and right
left_sort = self.merge_sort(left)
right_sort = self.merge_sort(right)
#merge tow result
if left_sort is None:
return right_sort
if right_sort is None:
return left_sort
new_head = ListNode(0)
cur = new_head
while(left_sort is not None and right_sort is not None):
if left_sort.val < right_sort.val:
cur.next = left_sort
left_sort = left_sort.next
else:
cur.next = right_sort
right_sort = right_sort.next
cur = cur.next
if left_sort is not None:
cur.next = left_sort
if right_sort is not None:
cur.next = right_sort
return new_head.next