1
class Solution {
2
public ListNode swapNodes(ListNode head, int k) {
3
ListNode fast = head;
4
ListNode slow = head;
5
ListNode first = head, second = head;
6

7
// Put fast (k-1) nodes after slow
8
for (int i = 0; i < k - 1; ++i) fast = fast.next;
9

10
// Save the node for swapping
11
first = fast;
12

13
// Move until the end of the list
14
while (fast.next != null) {
15
slow = slow.next;
16
fast = fast.next;
17
}
18

19
// Save the second node for swapping
20
// Note that the pointer second isn't necessary: we could use slow for swapping as well
21
// However, having second improves readability
22
second = slow;
23

24
// Swap values
25
int temp = first.val;
26
first.val = second.val;
27
second.val = temp;
28

29
return head;
30
}
31
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0