Skip to content

Commit 979fdd6

Browse files
authored
Update Swapping Nodes in a Linked List.java
1 parent 30b1345 commit 979fdd6

File tree

1 file changed

+34
-12
lines changed

1 file changed

+34
-12
lines changed

Medium/Swapping Nodes in a Linked List.java

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,44 @@
1010
*/
1111
class Solution {
1212
public ListNode swapNodes(ListNode head, int k) {
13-
ListNode fast = null;
13+
int listLength = 0;
1414
ListNode curr = head;
15-
int currCount = 1;
16-
while (currCount != k) {
15+
while (curr != null) {
16+
listLength++;
1717
curr = curr.next;
18-
currCount++;
1918
}
20-
fast = curr;
21-
ListNode slow = head;
22-
while (curr.next != null) {
23-
slow = slow.next;
24-
curr = curr.next;
19+
ListNode startPrev = null;
20+
ListNode start = head;
21+
ListNode endPrev = null;
22+
ListNode end = head;
23+
int count = k - 1;
24+
while (count > 0) {
25+
startPrev = start;
26+
start = start.next;
27+
count--;
28+
}
29+
count = listLength - k;
30+
while (count > 0) {
31+
endPrev = end;
32+
end = end.next;
33+
count--;
34+
}
35+
if (startPrev != null) {
36+
startPrev.next = end;
37+
}
38+
if (endPrev != null) {
39+
endPrev.next = start;
40+
}
41+
ListNode temp = start.next;
42+
start.next = end.next;
43+
end.next = temp;
44+
// Updating head pointers if required
45+
if (k == 1) {
46+
head = end;
47+
}
48+
if (k == listLength) {
49+
head = start;
2550
}
26-
int temp = fast.val;
27-
fast.val = slow.val;
28-
slow.val = temp;
2951
return head;
3052
}
3153
}

0 commit comments

Comments
 (0)