Swap Nodes in Pairs - Problem

Given the head of 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 nodes themselves may be changed).

For example, if the linked list is 1→2→3→4, the result should be 2→1→4→3.

Input & Output

Example 1 — Four Node List
$ Input: [1,2,3,4]
Output: [2,1,4,3]
💡 Note: Swap pairs (1,2) and (3,4): 1→2→3→4 becomes 2→1→4→3
Example 2 — Odd Length List
$ Input: [1,2,3]
Output: [2,1,3]
💡 Note: Swap pair (1,2), leave 3 unchanged: 1→2→3 becomes 2→1→3
Example 3 — Empty List
$ Input: []
Output: []
💡 Note: Empty list remains empty

Constraints

  • The number of nodes in the list is in the range [0, 100]
  • 0 ≤ Node.val ≤ 100

Visualization

Tap to expand
Swap Nodes in Pairs: [1,2,3,4] → [2,1,4,3]Before:1234Pair 1Pair 2SWAPAfter:2143Result: [2,1,4,3]
Understanding the Visualization
1
Input
Original linked list with nodes in sequential order
2
Process
Swap every two adjacent nodes by updating pointers
3
Output
Modified list with pairs swapped
Key Takeaway
🎯 Key Insight: Use pointer manipulation to swap adjacent pairs without modifying node values
Asked in
Facebook 42 Microsoft 38 Amazon 35 Google 28
425.0K Views
High Frequency
~15 min Avg. Time
9.0K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen