Swap Nodes in Pairs
Swap every two neighbouring nodes of a linked list by changing their links, not their values.
Given the head of a linked list, swap every two neighbouring nodes and return the head of the changed list. Only the links between the nodes may change, not the values stored in them. If the list has an odd number of nodes, the last node has no partner and stays where it is.
Example 1
Output: [2, 1, 4, 3]
Example 2
Output: [2, 1, 3]
Explanation: 1 and 2 swap places, and 3 has no partner, so it stays last.
The Idea
Picture people standing in a queue where each person only knows who stands right behind them. A linked list works the same way. Every node keeps its value and a link named nextnextnull
Take Example 1, [1, 2, 3, 4][2, 1, 4, 3]
Look at the picture below. It shows Example 1 halfway through, with the first pair already swapped: 2, 1, 3, 4. The next pair is 3 and 4. Call the first node of the pair abprev
In the row labelled before, prevaabbnullnull
So swapping a pair always means changing three links, and the rest of the list is not touched. The order matters too. Until link 1 is set, only bba
Solution Approach
Turning those three link changes into a loop over the whole list means settling three things: what plays prev
A node in front of the head
What is prev[1, 2, 3, 4]
The dummy node's nextprevdummy.next
When to stop
How do we know a full pair is still left? The pair starts right after prevprev.nextprev.next.next[1, 2, 3]prev
Moving to the next pair
Which node is prevabapreva
Java Solution
The method swapPairs
- First, create the dummy node with
, so itsnew ListNode(0, head) is the head. Its value, 0, is never read. Setnext toprev .dummy - Loop while
andprev.next are both notprev.next.next , so a full pair followsnull .prev - Inside the loop, name the pair:
isa andprev.next isb .a.next - Change the three links in order:
, thena.next = b.next , thenb.next = a .prev.next = b - Move
toprev , the second node of the swapped pair.a - When the loop ends, return
, the new head.dummy.next
The class also has a small ListNodebuildshowmain
public class SwapNodesInPairs {
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
while (prev.next != null && prev.next.next != null) {
ListNode a = prev.next;
ListNode b = a.next;
a.next = b.next; // a skips ahead to the node after the pair
b.next = a; // b now comes before a
prev.next = b; // the node before the pair now leads to b
prev = a; // a is the second node of the swapped pair
}
return dummy.next;
}
static ListNode build(int... values) {
ListNode head = null;
for (int i = values.length - 1; i >= 0; i--) {
head = new ListNode(values[i], head);
}
return head;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode n = head; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(swapPairs(build(1, 2, 3, 4))));
System.out.println(show(swapPairs(build(1, 2, 3))));
System.out.println(show(swapPairs(build(1, 2, 3, 4, 5, 6))));
System.out.println(show(swapPairs(build(7))));
System.out.println(show(swapPairs(build())));
}
}
Running it prints:
[2, 1, 4, 3]
[2, 1, 3]
[2, 1, 4, 3, 6, 5]
[7]
[]
Example 1 gives [2, 1, 4, 3][2, 1, 3][2, 1, 4, 3, 6, 5]prev[7][]
Moving prevbaprev.nextb[2, 3, 4, 1]prev
Complexity
The method walks the list once and does a fixed amount of relinking for each pair.
- Time: O(n), for a list of n nodes: each loop pass swaps one pair with three link changes and moves
two nodes forward, so the loop runs about n / 2 times.prev - Space: O(1). Besides the one dummy node, the method keeps only the references
,prev anda , and it reuses the existing nodes instead of building a new list.b
Swapping pairs is reversing the list in groups of two. For groups of any size, see