题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const inputs = []; rl.on("line", (line) => { inputs.push(line.split(" ")); }).on("close", () => { // 注意题目要求: 有多组样例输入,三行为一组 for (let i = 0; i < inputs.length; i += 3) { // 构造链表 const len = inputs[i]; const link_val = inputs[i+1]; let link = []; for (let i = 0; i < len; i++) { const node = { val: link_val[i], next: i < len - 1 ? i + 1 : null, pre: len - i }; link.push(node); } // K 在Node里是number类型,所以这里需要parseInt转一下 const reverseK = parseInt(inputs[i+2][0]); const node = searchNode(link, reverseK); console.log(node?.val); } }); // 按题目要求要正序构建链表,且忘记数组长度; // 那就只能正常按照链式解构去遍历数组,这种反转链表的多用双指针 // 本解是在node节点多设置一个指针,也就是节点倒序值 function searchNode(node, k) { let head = node[0]; while (head && head.next && head.pre !== k) { head = node[head.next]; } return head; }