LeetCode 刷题日记之链表中倒数第 k 个节点

解题思路:遍历出链表长度,设置一个计数点,当找到倒数第 K 个节点时返回,链表(感觉走了笨办法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var getKthFromEnd = function (head, k) {
let conut = 1;
let index = 1;
let temp = head;
while (temp && temp.next) {
conut++;
temp = temp.next;
}
while (head) {
if (conut - k + 1 === index) {
return head;
}
if (head.next) {
index++;
head = head.next;
} else {
head = null;
}
}
};