Swap Nodes in Pairs
1 approach, code in every language
Problem description
You are given the head of a singly linked list. Rearrange the list by exchanging each pair of adjacent nodes, so the first node trades places with the second, the third with the fourth, and so on.
If the list contains an odd number of nodes, the final leftover node keeps its position. You are not allowed to change the values stored inside the nodes; the swap must be performed purely by relinking the next pointers. Return the head of the modified list.
Example 1
Input: head = [1,2,3,4]
Output: [2,1,4,3]
The pair (1,2) becomes (2,1) and the pair (3,4) becomes (4,3).
Example 2
Input: head = [1,2,3]
Output: [2,1,3]
The first two nodes swap, while the lone trailing node 3 has no partner and stays where it is.
Constraints
The number of nodes in the list is in the range [0, 100].0 <= Node.val <= 100
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Swap Neighbouring Clips is our own problem on the technique behind Swap Nodes in Pairs: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free