A singly linked list starts at head and holds the nodes n0, n1, n2, …, nk in that order. Rearrange it so the nodes alternate between the front and the back: n0, nk, n1, nk−1, n2, nk−2, and so on, until every node has been placed once.
Change the next links, not the values stored in the nodes. The function returns nothing: the list starting at head should simply be in the new order.
Example 1
Input: head = [10, 20, 30, 40, 50] Output: [10, 50, 20, 40, 30] Why: first, last, second, second to last, then the middle
2 more examples and the constraints
Example 2
Input: head = [6, 7, 8, 9] Output: [6, 9, 7, 8] Why: with an even count, the two middle nodes end the list
Example 3
Input: head = [4] Output: [4] Why: a single node is already in order
Constraints
- 1 ≤ number of nodes ≤ 50,000
- 1 ≤ each node value ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy the nodes into an arrayO(n)
- Middle, reverse, mergeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 nodes | Verdict |
|---|---|---|---|
| Copy the nodes into an array | O(n) | Passes; uses O(n) memory | |
| Middle, reverse, merge | O(n) | Best; O(1) extra space |
n = number of nodes. Both are linear; the difference is the extra array.
Edge cases to test
- One node. [4] stays as it is; the middle is the head and the back half is empty.
- Two nodes. [1, 2] is already in order: first, then last.
- Even length. [6, 7, 8, 9] gives [6, 9, 7, 8]; the front half keeps one more node than you might expect.
- Odd length. The middle node ends the list and must point to null.
Common mistakes
- Forgetting
slow.next = null, which leaves a cycle after the weave. - Losing the rest of a half by overwriting
nextbefore saving it. - Swapping node values instead of relinking the nodes.
How to talk through it
- 1Clarify. Can I change the links but not the values? Is the list ever empty? Do I return anything?
- 2Start with the array. Copy nodes into an array to reach the back in O(1); say it costs O(n) memory.
- 3Spot the three parts. The back half is read backward, so reverse it; then the task is a plain merge.
- 4Code each part. Slow and fast pointers, cut, reverse, weave. Name each loop out loud.
- 5Test out loud. Run one node, two nodes, and an even and an odd length before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?