Problem Understanding
Take a singly linked list L0 → L1 → … → Ln - 1 → Ln and rearrange its nodes so they alternate between the front and the back, changing only the links and never the values:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
Example: 1->2->3->4 becomes 1->4->2->3.
Attempt 1: Array/Deque (Brute Force)
We can put all nodes into a Deque (Double Ended Queue). Then, we can pop from the front and back alternately to build the new list.
- Drawback: Uses O(N) extra space to store all node references.
Visualizing the Issue
We need access to the end of the list, but we only have a forward pointer. Does this remind you of Palindrome check? We needed to access the end there too.
The Intuition: Split, Reverse, Merge
- Find Middle: Split the list into two halves.
- Reverse Second Half: The second half starts at
slow.next. For1->2->3->4,slowstops at3, so the halves are1->2->3and4; for1->2->3->4->5they are1->2->3and4->5, reversed to5->4. - Merge: Pick one from first, then one from second.
1 -> 4 -> 2 -> 3.
Interactive Walkthrough
5 NODES · L0 → Ln → L1 → …
START AT HEAD
slow fast
#0
→
#1
→
#2
→
#3
→
#4
→ NULL
Phase
middle
slow and fast start at head, 1
Next
slow moves to 2; fast moves two to 3
Values
Watch the three steps as structure: the cut at slow.next = NULL turns one row into two, flipping the second half makes that row read backward, and each splice links a node from the lower row into the upper one until a single row remains.
