Practice › Linked List
Swap Nodes in Pairs
Medium · Linked List · Asked at Amazon, Microsoft, Meta, Bloomberg
Swap every two adjacent nodes — the 1st with the 2nd, the 3rd with the 4th, and so on — by changing links, not values. If the length is odd the last node stays. Print the list.
Input
First line: n. Second line: the n node values from head to tail.
Output
The list after swapping, space-separated.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ values ≤ 10^9
With a dummy node before the head: let a = prev.next and b = a.next; relink prev → b → a → (old b.next), then move prev to a.
Example 1
Input
4 1 2 3 4
Output
2 1 4 3
Example 2
Input
3 1 2 3
Output
2 1 3
Hints
- A dummy node before the head means the first pair is not a special case.
- For a pair a → b, three links change: prev → b, b → a, a → whatever came after b.
Approach
Keep prev, the node just before the next pair (initially the dummy). While two nodes follow it: a = prev.next, b = a.next; set a.next = b.next, b.next = a, prev.next = b; then prev = a (a is now the second node of the pair). Only links change — never values.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *next = nullptr;
Node(long long v) : val(v) {}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
Node dummy(0), *t = &dummy;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
t = t->next = new Node(x);
}
Node *prev = &dummy;
while (prev->next && prev->next->next) {
Node *a = prev->next, *b = a->next;
a->next = b->next;
b->next = a;
prev->next = b;
prev = a;
}
for (Node *p = dummy.next; p; p = p->next) cout << p->val << (p->next ? " " : "\n");
return 0;
}Python solution
import sys
class Node:
def __init__(self, val):
self.val, self.next = val, None
data = list(map(int, sys.stdin.read().split()))
dummy = tail = Node(0)
for v in data[1 : 1 + data[0]]:
tail.next = Node(v)
tail = tail.next
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
out, p = [], dummy.next
while p:
out.append(p.val)
p = p.next
print(*out)Java solution
import java.io.*;
public class Main {
static class Node {
long val;
Node next;
Node(long v) { val = v; }
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
Node dummy = new Node(0), t = dummy;
for (int i = 0; i < n; i++) {
in.nextToken();
t = t.next = new Node((long) in.nval);
}
Node prev = dummy;
while (prev.next != null && prev.next.next != null) {
Node a = prev.next, b = a.next;
a.next = b.next;
b.next = a;
prev.next = b;
prev = a;
}
StringBuilder sb = new StringBuilder();
for (Node p = dummy.next; p != null; p = p.next) sb.append(p.val).append(p.next != null ? " " : "\n");
System.out.print(sb);
}
}