Loading content...
You are given the head of a singly linked list containing n nodes. Your task is to rearrange the nodes by interleaving elements from the beginning and the end of the list, alternating between them.
The linked list can be visualized as:
N₀ → N₁ → N₂ → ... → Nₙ₋₂ → Nₙ₋₁
After rearrangement, the list should follow this pattern:
N₀ → Nₙ₋₁ → N₁ → Nₙ₋₂ → N₂ → Nₙ₋₃ → ...
The transformation pairs the first node with the last, the second node with the second-to-last, and so on, weaving them together into a single interleaved sequence.
Important: You must solve this problem by modifying the node connections themselves (in-place). You are not allowed to alter the values stored within the nodes—only the next pointers may be changed. The goal is to restructure the list without creating new nodes or using additional data structures proportional to the list size.
head = [1,2,3,4][1,4,2,3]The original list is 1 → 2 → 3 → 4. After rearrangement:
head = [1,2,3,4,5][1,5,2,4,3]The original list is 1 → 2 → 3 → 4 → 5. After rearrangement:
head = [1,2,3][1,3,2]The original list is 1 → 2 → 3. After rearrangement:
Constraints