题解 | #输出单向链表中倒数第k个结点#从尾部求出正序链表
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let lines = []; rl.on('line', function(line){ lines.push(line); if(lines.length === 3){ //构造链表 const arr = lines[1].split(' '); // 构造最后一个节点next为空 const last = new Node(arr[arr.length-1], null); let head = last; // 依次从后面来构建节点next为后面 for(let index = arr.length-2; index>=0; index--){ const newNode = new Node(arr[index], head); head = newNode; } //倒序节点算出正序节点 let count = lines[0] - lines[2]; while(count>0){ head = head.next; count--; } console.log(head.val); lines = []; } }); class Node{ constructor(val, next){ this.val = val; this.next = next; } }
#华为笔试#