Class Solution
java.lang.Object
g0001_0100.s0024_swap_nodes_in_pairs.Solution
24 - Swap Nodes in Pairs.
Medium
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
To solve the “Swap Nodes in Pairs” problem in Java with a Solution class, we can traverse the linked list while swapping pairs of nodes. Here are the steps:
- Define a
Solutionclass. - Define a method named
swapPairsthat takes the head of a linked list as input and returns the head of the modified list. - Create a dummy ListNode object and set its
nextpointer to the head of the input list. This dummy node will serve as the new head of the modified list. - Initialize three pointers:
prev,first, andsecond. - Iterate through the list while
firstandsecondare not null:- Assign
firstto thenextpointer ofprev. - Assign
secondto thenextpointer offirst. - Assign the
nextpointer ofprevto thenextpointer ofsecond. - Assign the
nextpointer ofsecondtofirst. - Move
prevtofirst. - Move
firsttofirst.next(which is the next pair of nodes).
- Assign
- Return the
nextpointer of the dummy node, which points to the head of the modified list.
Here’s the implementation:
public class Solution {
public ListNode swapPairs(ListNode head) {
// Create a dummy node and point its next to the head
ListNode dummy = new ListNode(0);
dummy.next = head;
// Initialize pointers
ListNode prev = dummy;
ListNode first, second;
// Swap pairs of nodes
while (prev.next != null && prev.next.next != null) {
first = prev.next;
second = first.next;
// Swap nodes
prev.next = second;
first.next = second.next;
second.next = first;
// Move prev to the next pair of nodes
prev = first;
}
return dummy.next;
}
}
This implementation provides a solution to the “Swap Nodes in Pairs” problem in Java without modifying the values in the list’s nodes.
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
swapPairs
-