Swap Nodes in Pairs
The key idea
Swap each adjacent pair by rewiring the three
next pointers around it — never by copying values. A dummy node placed before the head gives the very first pair a stable predecessor, so every pair (including the first) is rewired by the same uniform code with no special case.Problem
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only the nodes themselves may be changed). Each adjacent pair, such as the nodes holding 1 and 2, is reordered so the second comes first. If the list has an odd number of nodes, the final unpaired node keeps its position.
Constraints
- The number of nodes in the list is in the range
[0, 100]. 0 <= Node.val <= 100
Examples
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Input: head = []
Output: []
Input: head = [1]
Output: [1]
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Linked List problems
- Add Two NumbersMEDIUM
- Copy List with Random PointerMEDIUM
- Design Linked ListMEDIUM
- Insert Greatest Common Divisors in Linked ListMEDIUM
- Intersection of Two Linked ListsEASY
- Maximum Twin Sum of a Linked ListMEDIUM
- Merge Two Sorted ListsEASY
- Odd Even Linked ListMEDIUM
- Partition ListMEDIUM
- Remove Duplicates from Sorted List IIMEDIUM
- Remove Linked List ElementsEASY
- Remove Nth Node From End of ListMEDIUM