题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

function insertNode(head, curNodeVal, nextNodeVal) {
    let node = head;
    let p;
    while (node) {
        // find it
        if (node.val === curNodeVal) {
            p = node.next;
            node.next = {
                val: nextNodeVal,
                next: p,
            };
            return;
        }
        node = node.next;
    }
    return;
}
function genList(head, array) {
    if (array.length % 2 !== 0) {
        throw new Error('输入有误!');
    }
    let nextNodeVal;
    let curNodeVal;
    while (array.length) {
        nextNodeVal = array.shift();
        curNodeVal = array.shift();
        insertNode(head, parseInt(curNodeVal, 10), parseInt(nextNodeVal, 10));
    }
}
function deleteTargetNode(head, targetNodeVal) {
    let node = head;
    let pre;
    let p;
    while (node) {
        // find it
        if (node.val === targetNodeVal) {
            p = node.next;
            pre.next = p;
            return;
        }
        pre = node;
        node = node.next;
    }
}
function formatList(head) {
    const res = [];
    let node = head;
    while (node) {
        res.push(node.val);
        node = node.next;
    }
    return res.join(' ');
}
while (line = readline()) {
    var lines = line.split(' ');
    const listCnt = parseInt(lines[0], 10);
    let head = {
        val: parseInt(lines[1], 10),
        next: null,
    };
    try {
        genList(head, lines.slice(2, lines.length - 1));
    } catch (err) {
        print(err);
    }
    deleteTargetNode(head, parseInt(lines[lines.length - 1], 10));
    print(formatList(head));
}

#数据结构编程链表#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 10:39
一个证都没 我能填什么
程序员小白条:别人有,你为什么没有,还是这个道理,社会就是比较,竞争,淘汰,你要安逸,那么就要做好淘汰的准备
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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