Skip to content

Commit 3df6acb

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
reorder-list.py
1 parent 35a6a05 commit 3df6acb

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

problems/reorder-list.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
The reorder list, we can see it as
3+
smallest, largest, 2th smallest, 2th largest, 3th smallest...
4+
5+
First, put the ordered nodes in a stack, so we can get the largest node by `pop()`.
6+
And count how many nodes in total.
7+
8+
Second, because the node is already ordered
9+
So we only need to insert a large node between every node until we hit the count.
10+
11+
Last, remember to put `None` at the end.
12+
13+
The tricky part is there may be even count or odd count of nodes in total.
14+
When face problem like this, you should approach these test cases by hand.
15+
Think about the edge cases. Here:
16+
1->2->3->4
17+
1->2->3->4->5
18+
"""
19+
class Solution(object):
20+
def reorderList(self, head):
21+
if head is None: return
22+
h = head
23+
curr = head
24+
stack = []
25+
count = 0
26+
27+
while curr:
28+
count+=1
29+
stack.append(curr)
30+
curr = curr.next
31+
32+
while count>1:
33+
temp = h.next
34+
h.next = stack.pop()
35+
h.next.next = temp
36+
count-=2
37+
h = h.next.next
38+
39+
h.next = None

0 commit comments

Comments
 (0)