-
Notifications
You must be signed in to change notification settings - Fork 481
/
0143.py
63 lines (52 loc) · 1.38 KB
/
0143.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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head == None or head.next == None:
return
pre = head
lat = head.next
while lat != None and lat.next != None:
pre = pre.next
lat = lat.next.next
p = pre.next
pre.next = None
# reverse
cur = None
while p != None:
q = p.next
p.next = cur
cur = p
p = q
pre = head
while pre != None and cur != None:
tmp = cur.next
cur.next = pre.next
pre.next = cur
pre = pre.next.next
cur = tmp
def createList():
head = ListNode(1)
cur = head
for i in range(2, 5):
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)
Solution().reorderList(head)
printList(head)