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

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

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));
}

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

相关推荐

千疮百孔的象牙塔:我也在捣鼓im,你这个im好奇怪的样子,单看简历get不到点,im的消息及时性,消息可靠性,然后系统的可扩展性这几个关键问题都是怎么解决的从简历描述get不到,具体说消息怎么传,消息怎么推送,消息怎么存,消息安全怎么做的这些点感觉对应不起来
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务