Topic describes

Their thinking

  • The problem uses the idea of fast and slow pointer.
  • The fast pointer takes k steps first.
  • Then the fast and slow hands move in sync.
  • When the next field of the fast pointer is empty, the slow pointer takes one more step to reach the penultimate KTH node.
  • In this case, if there is only one node in the list, the head pointer of the node is directly returned.

The implementation code

var getKthFromEnd = function(head, k) {
    // In this case, we use the method of fast and slow pointer
    // First define a fast pointer
    let fast = head;
    let slow = head;
    for(let i = 1; i <= k; i++) { fast = fast.next; }if(fast === null) {
        return head;
    }
    while (fast.next) {
        fast = fast.next;
        slow = slow.next;
    }
    slow = slow.next;

    return slow;
};
Copy the code