题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 使用类的时候才会用到的
class MyNode {
// 由于运行的时候,报错说MyNode,没有next 属性,所以才会出此下策
value: any;
next: any;
constructor(value, next){
this.value = value
this.next = next
}
}
let [row, k,valueList] = [0, undefined, undefined]
rl.on('line', function (line) {
row++
if(row % 2 === 0){
valueList = line.split(' ').map(Number)
}else if(row % 3 === 0){
row = 0
k = Number(line)
// 数组方式--通过
// showNodeByArray(valueList, k)
// class 方式
showNodeByClass(valueList, k)
}
});
// 方式一,数组方式
function showNodeByArray(valueList: number[], k: number){
// 将数组倒过来
valueList.reverse()
// ?? 的啥意思就是左侧的值为 null 或 undefined 时 使用右侧的数据
console.log(valueList[k-1] ?? '')
}
// 方式二,class 类方式
function showNodeByClass(valueList: number[], k: number){
/**
* 构建列表,使用尾插法
* 1、创建头结点,指向空
* 2、遍历使用尾插法,插入节点(应题目要求,正序构建链表)
* 3、获取倒数第k个节点
*/
// 头结点
let head = new MyNode(valueList[0], null)
// 当前节点,用于插入节点时,找到对应的位置
let curNode = head
// 正序构建列表
for(let i = 1; i < valueList.length; i++){
// 创建节点,但是节点先不指向
let node = new MyNode(valueList[i], null)
// 让链表的最后一个节点接上新创建的节点
curNode.next = node
// 再让当前节点移到最后一个节点
curNode = node
}
let cur = head
// 1 2 3 4 5 6 7 8, 这组数据倒数第二个 不就是 valueList[8-2]-->valueList[6] = 7
let n = valueList.length - k
while(cur != null && n){
cur = cur.next
n--
}
// 打印倒数第k个节点, n遍历完后,得到的cur就是目标节点
console.log(cur.value ?? '')
}

