题目
输入一个链表,输出该链表中倒数第k个结点。
function ListNode(x){
this.val = x;
this.next = null;
}
code
// 1 -> 2 -> 3 -> 4
// 倒数第1:index = 3 len = 4 index = len - 1
// 倒数第2:index = 2 len = 4 index = len - 2
// 倒数第3:index = 1 len = 4 index = len - 3
// 倒数第4:index = 0 len = 4 index = len - 4
function findKthToTail(head, k) {
// write code here
// 获取链表的长度
let cur = head
let length = 0
while (cur) {
length++
cur = cur.next
}
let index = length - k
if (index < 0 || index >= length) return null
// 现在也就是找出第index节点
cur = head
while (index) {
cur = cur.next
index--
}
return cur
}