-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy path143 Reorder List.py
50 lines (43 loc) · 1.23 KB
/
143 Reorder 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
'''
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head:
return
# split
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
head1, head2 = head, slow.next
slow.next = None
# reverse
cur, pre = head2, None
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
# merge
cur1, cur2 = head1, pre
while cur2:
nex1, nex2 = cur1.next, cur2.next
cur1.next = cur2
cur2.next = nex1
cur1, cur2 = nex1, nex2
if __name__ == "__main__":
None