题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// 给ts的可怜娃一个标准答题思路。垃圾牛客 参数输入获取简直巨坑!!!!!!
class LinkList {
value: number;
next: LinkList;
constructor(arr: number[]) {
let node = null;
let current = null;
for (let val of arr) {
const cur = {
value: val,
next: null,
};
if (node) {
current.next = cur;
current = current.next;
} else {
node = cur;
current = node;
}
}
this.value = node.value;
this.next = node.next;
}
}
const linesAll = [];
rl.on("line", function (line) {
linesAll.push(line);
});
rl.on("close", function () {
const len = linesAll.length
for (let x = 0; x < len; x = x + 3) {
const lines = linesAll.splice(0, 3);
// console.log(lines);
const node = new LinkList(lines[1].split(" ").map((i) => Number(i)));
const k = lines[2];
let link1 = node;
let link2 = node;
let i = 0;
// 核心思路,找另一个链表先移动k次,这样两个链表同时到达终点的时候,长链表一定到达k的位置
while (i < k) {
link1 = link1.next;
i++;
}
while (link1 && link2) {
link1 = link1.next;
link2 = link2.next;
}
console.log(link2.value);
}
});
文远知行公司福利 534人发布