Skip to content

Commit 3e7337b

Browse files
authored
Added Swapping Nodes in a Linked List.java
1 parent 7f5b7e5 commit 3e7337b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode swapNodes(ListNode head, int k) {
13+
ListNode fast = null;
14+
ListNode curr = head;
15+
int currCount = 1;
16+
while (currCount != k) {
17+
curr = curr.next;
18+
currCount++;
19+
}
20+
fast = curr;
21+
ListNode slow = head;
22+
while (curr.next != null) {
23+
slow = slow.next;
24+
curr = curr.next;
25+
}
26+
int temp = fast.val;
27+
fast.val = slow.val;
28+
slow.val = temp;
29+
return head;
30+
}
31+
}

0 commit comments

Comments
 (0)