-
Notifications
You must be signed in to change notification settings - Fork 481
/
0148.py
67 lines (53 loc) · 1.48 KB
/
0148.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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def _merge(self, head1, head2):
if head1 == None or head2 == None:
return head2 or head1
h = ListNode(-1)
tmp = h
while head1 != None and head2 != None:
if head1.val < head2.val:
tmp.next = head1
head1 = head1.next
else:
tmp.next = head2
head2 = head2.next
tmp = tmp.next
tmp.next = head1 or head2
return h.next
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
lat = pre = head
while lat.next != None and lat.next.next != None:
lat = lat.next.next
pre = pre.next
lat = pre.next
pre.next = None
return self._merge(self.sortList(head), self.sortList(lat))
def createList():
head = ListNode(0)
cur = head
for i in range(1, 6):
cur.next = ListNode(i)
cur = cur.next
return head
def printList(head):
cur = head
while cur != None:
print(cur.val, '-->', end='')
cur = cur.next
print('NULL')
if __name__ == "__main__":
head = createList()
printList(head)
res = Solution().sortList(head)
printList(res)