题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; const createList = (tokens, length, head, cb) => { let index = 2; while (index < length * 2 - 1) { let a = tokens[index]; index++; let b = tokens[index]; index++; cb(b, a); } return head; }; class List { constructor(val) { this.head = this.createNode(val); } getHead() { return this.head; } createNode(val = null, next = null) { return { val, next, }; } insertNode(head, node, val) { let curr = head; while (curr != null && curr.val != null) { if (curr.val === node) { const next = curr.next; curr.next = this.createNode(val); curr.next.next = next; curr = curr.next; break; } else { curr = curr.next; } } } printNode() { let curr = this.head; let printArr = []; while (curr != null) { printArr.push(curr.val); curr = curr.next; } console.log(printArr.join(" ")); } deleteNodeFn(deleteNode) { let curr = this.head; let pre = this.createNode(null, curr); while (curr.next) { if (pre.val == null && curr.val === deleteNode) { this.head = curr.next; break; } pre = curr; curr = curr.next; if (curr.val === deleteNode) { if (curr.val == null) { pre.next = null; } else { pre.next = curr.next; } break; } } } } void async function () { // Write your code here while (line = await readline()) { let tokens = line.split(" "); const length = tokens[0]; const deleteNode = tokens.pop(); const list = new List(tokens[1]); const head0 = list.getHead(); createList(tokens, length, head0, (b, a) => { list.insertNode(head0, b, a); }); list.deleteNodeFn(deleteNode); list.printNode(); } }()