题目描述
解题思路
快慢指针
fast
先走k步,然后slow
开始走- 当
fast
走到最后的时候,开始遍历slow
就可以输出后面的链表
代码实现
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var getKthFromEnd = function(head, k) {
let [fast, slow] = [head, head];
for (let i=0; i<k; i++) {
fast = fast.next;
};
while (fast) {
fast = fast.next;
slow = slow.next;
};
return slow;
};