-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148.py
43 lines (42 loc) · 1 KB
/
148.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
if not head.next:
return head
slow = head
fast = head.next
while fast:
fast = fast.next
if not fast:
break
fast = fast.next
slow = slow.next
B = self.sortList(slow.next)
slow.next = None
A = self.sortList(head)
res = ListNode(0)
tag = res
while A and B:
if A.val < B.val:
tag.next = A
tag = A
A = A.next
else:
tag.next = B
tag = B
B = B.next
if A:
tag.next = A
if B:
tag.next = B
return res.next