LeetCode #24: Swap Nodes in Pairs — Solved in Java
Pairwise Recursion and Iterative Swaps with a Dummy Head
LeetCode’s Swap Nodes in Pairs problem asks you to take a linked list and exchange every two adjacent nodes without changing the node values. The first node swaps with the second, the third swaps with the fourth, and so on until you reach the end of the list. The goal is to rebuild the list so every pair trades places, keeping all connections valid from start to finish.
Thinking through it in Java, it helps to picture each node as a small link that connects forward to the next one. Swapping pairs means those links have to be rearranged carefully so nothing breaks in the chain of nodes. A recursive solution handles this neatly by flipping the first two and letting the same process handle the rest, while an iterative solution takes the hands-on route by walking the list and updating the pointers in place. Both share the same end goal of producing a properly connected list where every two nodes have swapped without losing the original structure.
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 nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
Constraints:
The number of nodes in the list is in the range
[0, 100].
0 <= Node.val <= 100/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
Keep reading with a 7-day free trial
Subscribe to Alexander Obregon's Substack to keep reading this post and get 7 days of free access to the full post archives.


