-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreorderList.py
99 lines (78 loc) · 2.13 KB
/
reorderList.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
1->2->3->4->5->6,
# Split middle
1->2->3 4->5->6,
# Reorder Right
1->2->3 6->5->4,
# Weave two lists
1->6->2->5->3->4
"""
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev, curr = None, slow
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
first, second = head, prev
tmp = None
while second.next:
tmp = first.next
first.next = second
first = tmp
tmp = second.next
second.next = first
second = tmp
"""
1->2->3->4->5->6,
# Split middle
1->2->3 4->5->6,
# Reorder Right
1->2->3 6->5->4,
# Weave two lists
1->6->2->5->3->4
"""
class Solution:
def reorderList(self, head:ListNode):
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
slow = fast = head
# Get midpoint
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Reverse 2nd half
prev, curr = None, slow
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
first, second = head, prev
tmp = None
# Weave, 2 at a time
while second.next:
tmp = first.next
first.next = second
first = tmp
tmp = second.next
second.next = first
second = tmp