Input a linked list, output the last KTH node of the list. 1 find the length of the list 2 take n minus k steps from the starting point
Note:
k >= 1; If k is greater than the list length, NULL is returned;
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; *} * /
/ * * *@param {ListNode} pListHead
* @param {number} k
* @return {ListNode}* /
var findKthToTail = function(pListHead, k) {
// Find the length of the list first
let cur = pListHead;
let n = 0;
while(cur){
n++;
cur = cur.next;
}
// The penultimate KTH node takes n-k steps
cur = pListHead;
if(k > n) return null;
for(let i = 0; i < n - k; i ++){
cur = cur.next;
}
return cur;
};
Copy the code