
Sponsored
Sponsored
This approach involves two passes through the linked list. In the first pass, we determine the kth node from the beginning. In the second pass, we find the kth node from the end. Once we have both nodes, we swap their values. This approach requires a complete traversal of the list during each pass, but is simple to implement.
Time Complexity: O(n) due to two linear passes through the list. Space Complexity: O(1) since we use only pointers.
1class ListNode {
2 int val;
3 ListNode next;
4 ListNode(int x) { val = x; }
5}
6
7public class Solution {
8 public ListNode swapNodes(ListNode head, int k) {
9 int length = 0;
10 ListNode first = head;
11 ListNode second = head;
12 ListNode current = head;
13
14 while (current != null) {
15 length++;
16 if (length == k) {
17 first = current;
18 }
19 current = current.next;
20 }
21
22 current = head;
23 for (int i = 0; i < length - k; i++) {
24 current = current.next;
25 }
26 second = current;
27
28 int temp = first.val;
29 first.val = second.val;
30 second.val = temp;
31
32 return head;
33 }
34}
35The Java approach follows a similar logic where we traverse the list twice. The first traversal helps to find the kth node from the beginning and calculates the total length. The second loop determines the kth node from the end. Finally, it swaps the values of both nodes.
This approach optimizes the two-pass technique by using a single traversal with two pointers method. The idea is to leverage two pointers where one pointer reaches the kth node while the other starts marking the start from the head. Once the first pointer reaches the end, the second pointer will be at the correct kth position from the end. We then swap the values directly.
Time Complexity: O(n), as we make only one pass of the list. Space Complexity: O(1).
This C solution uses two pointers, fast and slow. Initially, fast moves k steps ahead. While it goes till the end, the slow pointer marks the kth position from the end. Thus, after the loop, we hold references to both kth from start and end, allowing us to swap their values.