Problem
Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example 1:
1 | |
Example 2:
1 | |
Explanation
-
Make a
curpointer to the head, while the pointer is not null, pushcurpointer’s node to the stack. -
Note, if there are 4 nodes like
1->2->3->4, then we only need to popn = (stack.size()-1)/2 = (4-1)/2 = 1time. Because we just want to connect1->4, but2->3is already connected. After we finish popingntimes, we set3->null, which isst.peek().next = null. -
Make
curpointer points back to the head. Now the top node of the stack is the next node ofcur. We can pop it and set it tocur.nextand move thecurto the right position and decrease the counter.
Solution
1 | |