题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
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));
}
#数据结构编程链表#
荣耀工作强度 439人发布