题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    class Node {
        constructor(val, next) {
            this.val = val;
            this.next = next;
        }
    }

    const create = (values) => {
        const head = new Node(values[0], null);
        let p = head;
        for (let i = 1; i < values.length; i++) {
            let val = values[i];
            let node = new Node(val, null);
            p.next = node;
            p = node;
        }
        return head;
    };

    let array = [];
    let n = [];
    let k = [];
    let index = 0;

    while ((line = await readline())) {
        switch (index % 3) {
            case 0:
                n.push(parseInt(line));
                break;
            case 1:
                array.push(line.split(" "));
                break;
            case 2:
                k.push(parseInt(line));
                break;
        }
        index++;
    }

    for (let j = 0; j < array.length; j++) {
        let p = create(array[j]);
        for (let i = 2; i <= n[j] - k[j] + 1; i++) {
            // 倒数第k个结点,即正数第n-k+1个结点
            p = p.next;
        }
        console.log(p.val);
    }
})();

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务