-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148. Sort List.py
46 lines (39 loc) · 1.01 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
# 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
"""
if not head or not head.next:
return head
slow = head
fast = head.next
# find mid
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
left = self.sortList(head)
right = self.sortList(mid)
# merge
t = ans = ListNode(0)
while left and right:
if left.val < right.val:
t.next = left
left = left.next
else:
t.next = right
right = right.next
t = t.next
if left:
t.next = left
else:
t.next = right
return ans.next