File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments