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

[B] [C] [D]

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).

Example 1:

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

Example 2:

Input: the head =,9,6,6,7,8,3,0,9,5 [7], k = 5 output:,9,6,6,8,7,3,0,9,5 [7]Copy the code

Example 3:

Input: head = [1], k = 1 output: [1]Copy the code

Example 4:

Input: head = [1,2], k = 1 output: [2,1]Copy the code

Example 5:

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

Tip:

  • The number of nodes in the linked list is zeron
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

The solution is as follows:

  1. definenextThe pointer initializes pointinghead
  2. nextThe needle goes backwardsk-1Step, find the positive numberkA node
  3. nextThe pointer moves one step further back fromheadThe node position is gonek
  4. headPointers andnextThe hands go backwards together untilnextPointer tonullAt this time,headThe pointer points to the penultimatekA node
  5. Swap positive oneskTwo nodes and the reciprocalkThe value of a node
  6. Return to the head node

The code is as follows:

var swapNodes = function(head, k) { let pre = null, cur = head; const vhead = new ListNode(0); vhead.next = head; While (k){if(k===1) pre = cur; cur = cur.next,k--; } while(cur){ cur = cur.next; head = head.next; } const headVal = head.val; head.val = pre.val; pre.val = headVal; return vhead.next; };Copy the code

At this point we are done with the nodes in the Leetcode-1721-swap linked list

If you have any questions or suggestions, please leave a comment!