“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Give you the head node of the list, head, and an integer k.

After swapping the value of the positive and penultimate KTH node of the list, return the head node of the list (the list is indexed from 1).

Input: head = [1,2,3,4,5], k = 2 output: [1,4,3,2,5] example 2:Copy the code

Input: head = [7,9,6,6,7,8,3,0,9,5] output: [7,9,6,6,8,7,3,0,9,5] example 3: input: head = [1], k = 1 output: [1] example 4: input: Output: [2,1] Example 5: Input: head = [1,2,3], k = 2 Output: [1,2,3]Copy the code

In this case, we have a linked list head and an integer k, and we need to swap the values of k from front to back and from back to front, so we need to know the value of the positive KTH node, and the value of the penultimate KTH node. Since we do not know the length of the node, we cannot know which node is the KTH penultimate value in the case of a positive number. In this problem, we can use the double-pointer method. We assume that the fast pointer and slow pointer both point to head. And then the length of the node becomes the length of the head minus the value of K and let’s say it’s a K2 node, and then the slow node just needs to go to this node and that’s the value of the KTH node from back to front.

That is, if the length is 5 and K is 2, then the reciprocal K is 3, which is 5 minus 2 is 3.

So we use code to do that

Var swapNodes = function (head, k) {var swapNodes = function (head, k) {var swapNodes = function (head, k) { let fast = head; let slow = head; // count = 1; // iterate over the termination condition while (dummy.next! = null) {// count < k, If (count < K) {fast = fast. Next count++} else {// Slow = slow. Next} dummy = dummy.next } const temp = fast.val; fast.val = slow.val; slow.val = temp; return head };Copy the code

Because we only need to replace val of two nodes, we do not need to worry about the next node, so we can directly replace val. If it is to replace two nodes, then we also need to replace next and assign the last null on this basis, otherwise a closed loop will be formed.