
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.
1#include <iostream>
2
3struct ListNode {
4 int val;
5 ListNode* next;
6 ListNode(int x) : val(x), next(nullptr) {}
7};
8
9ListNode* swapNodes(ListNode* head, int k) {
10 int length = 0;
11 ListNode* first = head;
12 ListNode* second = head;
13 ListNode* current = head;
14
15 for (; current != nullptr; current = current->next) {
16 length++;
17 if (length == k) {
18 first = current;
19 }
20 }
21
22 current = head;
23 for (int i = 0; i < length - k; i++) {
24 current = current->next;
25 }
26 second = current;
27
28 std::swap(first->val, second->val);
29
30 return head;
31}
32The C++ solution also follows a similar idea as the C example. We calculate the length of the list and find the k-th nodes from the beginning and the end, then swap their values using std::swap().
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.