Skip to content

Commit bb98228

Browse files
committed
solve : reorder-list
1 parent 6b99c02 commit bb98228

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

reorder-list/samthekorean.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# TC : O(n)
2+
# SC : O(m) m being the sum of deque and dummy nodes
3+
class Solution:
4+
def reorderList(self, head: Optional[ListNode]) -> None:
5+
if not head or not head.next or not head.next.next:
6+
return
7+
8+
# Step 1: Use a deque to collect nodes
9+
d = deque()
10+
current = head
11+
while current:
12+
d.append(current)
13+
current = current.next
14+
15+
# Step 2: Reorder the list using deque
16+
dummy = ListNode(0) # Dummy node with value 0
17+
current = dummy
18+
toggle = True
19+
20+
while d:
21+
if toggle:
22+
current.next = d.popleft() # Append from the front of the deque
23+
else:
24+
current.next = d.pop() # Append from the back of the deque
25+
current = current.next
26+
toggle = not toggle
27+
28+
# Step 3: Ensure the last node points to None
29+
current.next = None
30+
31+
# Step 4: Reassign head to point to the new reordered list
32+
head = dummy.next

0 commit comments

Comments
 (0)