Skip to main content

链表中倒数第 k 个节点

题目

给定一个链表, 找到该链表倒数第 k 个节点.

示例

输入: 1->2->3->4->5->NULL, k = 2

输出: 4->5->NULL

题解

让快指针先走 k 步, 再快慢指针往前一起走, 快指针走到头了, 慢指针就指向了链表中倒数第 k 个节点.

/**
* 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 = head,
slow = head

while (k > 0) {
fast = fast.next
k--
}

while (fast) {
fast = fast.next
slow = slow.next
}

return slow
}