Swap Nodes in Pairs
Medium
Linked ListRecursion
Problem
Given the head of a linked list, swap every two adjacent nodes and return the new head. Must swap nodes, not just values.
Example 1
Input: [1,2,3,4]
Output: [2,1,4,3]
Constraints
- 0 ≤ length ≤ 100
Approach — Linked List
This is a Linked List problem. The idea: rework the list with careful pointer manipulation — often a dummy head and fast/slow pointers — in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) space.
Solution code
Python
class Solution:
def swapPairs(self, head):
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next:
a = prev.next
b = a.next
a.next = b.next
b.next = a
prev.next = b
prev = a
return dummy.next
Java
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode second = head.next;
head.next = swapPairs(second.next);
second.next = head;
return second;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Swap Nodes in Pairs interactively → ← All solutions