Example 1
- Input
- head = [1,2,3,4]
- Output
- [1,4,2,3]
Take node 1 from the front and node 4 from the back, then take nodes 2 and 3. All four original nodes remain in the list and node 3 becomes the null-terminated tail.
Given the head of a singly linked list, reorder its nodes in place to alternate from the front and the back (first, last, second, second-last, and so on) without changing any node values.
Given the head of an acyclic singly linked list, rearrange its nodes in place by taking the first node, the last node, the second node, the second-last node, and continuing inward until every node appears once.
Change only the next links. Do not change values or replace nodes with copies. The head remains the same node, the final tail points to null, and the procedure returns no new list.
Take node 1 from the front and node 4 from the back, then take nodes 2 and 3. All four original nodes remain in the list and node 3 becomes the null-terminated tail.
The pairs are 1 with 5 and 2 with 4. The middle node 3 has no partner, so it appears once at the tail; the first half must be at least as long as the second.
There is only one original node. It is both head and tail, so its value and null next link stay unchanged.
Repeated values do not identify nodes: the order uses original positions 0, 3, 1, 2. Swapping integer values would not satisfy the required node rearrangement.
The target order needs access to both ends, but a singly linked list only walks forward. For Example 1, the front supplies 1 then 2 while the back supplies 4 then 3. An array of node references provides backward access directly; the constant-space alternative splits the list and reverses the back half, making the required back-to-front order available as a forward walk. In either method, save access to the remaining nodes before changing their links.
Reveal Store Nodes in Array: intuition, complexity, and code
slow.next before reversing allows an old link between halves to create a cycle during the merge.When both ends of a list are needed at once, split at the middle, reverse the back half, then walk the halves together.