“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]

Input a linked list, output the last KTH node of the list. In order to conform to the convention of most people, this case counts from 1, i.e. the last node of the list is the last node from the last.

For example, a linked list has six nodes, starting with the head node, whose values are 1, 2, 3, 4, 5, and 6. The third from last node of the list is the node with the value 4.

Example:

Given a linked list: 1->2->3->4->5, and k = 2. Return to list 4->5.Copy the code

The solution is as follows:

  1. definenextThe pointer initializes pointinghead
  2. letnextThe needle goes backwardsk
  3. letheadPointers andnextThe hands go backwards together untilnextPoint to thenull
  4. At this timeheadThe pointer points to the penultimatekA node

The code is as follows:

var getKthFromEnd = function(head, k) { let next = head; While (k){next = next-next; k--; } // head next goes backwards until next goes to the end of the list // head points to the last KTH node while(next){head = head. Next; next = next.next; } return head; };Copy the code

At this point we are done with leetcode- Finger Offer 22- the KTH last node in the linked list

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