You get the head of a singly linked list. Swap the first node with the second, the third with the fourth, and so on through the list. If the length is odd, the last node has no partner and stays where it is.
Do it by changing the links between nodes, not by swapping the values stored in them. Return the head of the new list.
Example 1
Input: head = [7, 2, 9, 5] Output: [2, 7, 5, 9] Why: 7 and 2 trade places, then 9 and 5
2 more examples and the constraints
Example 2
Input: head = [8, 1, 6] Output: [1, 8, 6] Why: 6 has no partner, so it stays last
Example 3
Input: head = [] Output: [] Why: an empty list has nothing to swap
Constraints
- The list has between 0 and 100 nodes
- 0 ≤ each node value ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- RecursionO(n)
- Dummy node, three links per pairO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes | Verdict |
|---|---|---|---|
| Recursion | O(n) | Passes; uses the call stack | |
| Dummy node, three links per pair | O(n) | Best; constant extra space |
n = number of nodes. Both do the same link changes; recursion also pays for n / 2 calls.
Edge cases to test
- Empty list. Return null; the loop never runs.
- One node. [4] stays [4]: it has no partner.
- Odd length. The last node keeps its place, and the node before it must still point at it.
- Equal values. [3, 3] looks unchanged, but the nodes themselves must still trade places.
Common mistakes
- Setting
b.next = abefore savingb.next, which cuts off the rest of the list. - Forgetting
prev.next = b, so the node before the pair still points at a. - Swapping the values instead of the nodes, which the problem forbids.
How to talk through it
- 1Clarify. What happens to a last odd node? May I swap values, or must I move the nodes?
- 2Draw one pair. prev → a → b → next becomes prev → b → a → next: three links change.
- 3Add a dummy. It gives the first pair a "prev" too, so the head needs no special case.
- 4Code the loop. Say the order of the three assignments and why a.next must be set first.
- 5Test out loud. Run the empty list, one node, 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?