You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md
+50-1Lines changed: 50 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -35,4 +35,53 @@ Given a linked list, swap every two adjacent nodes and return its head. You must
35
35
**Constraints:**
36
36
37
37
* 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
+
publicclassSolution {
59
+
publicListNodeswapPairs(ListNodehead) {
60
+
// Create a dummy node and point its next to the head
61
+
ListNode dummy =newListNode(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