Skip to content

Commit a4c0dee

Browse files
authored
Update README with 'Swap Nodes in Pairs' solution
Added a detailed explanation and implementation for the 'Swap Nodes in Pairs' problem in Java to the README file.
1 parent 53b3ca0 commit a4c0dee

File tree

1 file changed

+50
-1
lines changed
  • src/main/java/g0001_0100/s0024_swap_nodes_in_pairs

1 file changed

+50
-1
lines changed

src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,53 @@ Given a linked list, swap every two adjacent nodes and return its head. You must
3535
**Constraints:**
3636

3737
* The number of nodes in the list is in the range `[0, 100]`.
38-
* `0 <= Node.val <= 100`
38+
* `0 <= Node.val <= 100`
39+
40+
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:
41+
42+
1. Define a `Solution` class.
43+
2. Define a method named `swapPairs` that takes the head of a linked list as input and returns the head of the modified list.
44+
3. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list.
45+
4. Initialize three pointers: `prev`, `first`, and `second`.
46+
5. Iterate through the list while `first` and `second` are not null:
47+
- Assign `first` to the `next` pointer of `prev`.
48+
- Assign `second` to the `next` pointer of `first`.
49+
- Assign the `next` pointer of `prev` to the `next` pointer of `second`.
50+
- Assign the `next` pointer of `second` to `first`.
51+
- Move `prev` to `first`.
52+
- Move `first` to `first.next` (which is the next pair of nodes).
53+
6. Return the `next` pointer of the dummy node, which points to the head of the modified list.
54+
55+
Here's the implementation:
56+
57+
```java
58+
public class Solution {
59+
public ListNode swapPairs(ListNode head) {
60+
// Create a dummy node and point its next to the head
61+
ListNode dummy = new ListNode(0);
62+
dummy.next = head;
63+
64+
// Initialize pointers
65+
ListNode prev = dummy;
66+
ListNode first, second;
67+
68+
// Swap pairs of nodes
69+
while (prev.next != null && prev.next.next != null) {
70+
first = prev.next;
71+
second = first.next;
72+
73+
// Swap nodes
74+
prev.next = second;
75+
first.next = second.next;
76+
second.next = first;
77+
78+
// Move prev to the next pair of nodes
79+
prev = first;
80+
}
81+
82+
return dummy.next;
83+
}
84+
}
85+
```
86+
87+
This implementation provides a solution to the "Swap Nodes in Pairs" problem in Java without modifying the values in the list's nodes.

0 commit comments

Comments
 (0)