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
cur
pointer to the head, while the pointer is not null, pushcur
pointer’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 = 1
time. Because we just want to connect1->4
, but2->3
is already connected. After we finish popingn
times, we set3->null
, which isst.peek().next = null
. -
Make
cur
pointer 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.next
and move thecur
to the right position and decrease the counter.
Solution
1 |
|