题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
别看代码多,实际思路非常简单
- 先将数据分成 num, start, arr, del 四部分,start是初始值,arr就是链表所有值,del,是需要删除的部分
- 将arr 2个2个的处理一下,如1 2 3 2 5 1 4 5 7 2 处理成 [21,32,15,54,27] 其中的数字实际是数组,再14行可以打印看看
- 初始化一个链表 [start]
- 循环 nodeList ,去nodes里面找到nodeList[i] 的第0项,如果有,则把第一项splice进去后一项。注意:这里不用判断是第一项还是最后一项还是中间的某一项,反正用的splice
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
let [num, start,...arr] = (await readline()).split(" ")
let del = arr.pop()
// 1 2 3 2 5 1 4 5 7 2
let nodeList = []
for(let i = 0;i<arr.length;i+=2){
nodeList.push([arr[i+1],arr[i]])
}
// console.log(nodeList)
// nodeList // [2,1],[3,2],[5,1],[5,4],[2,7]
let nodes = [start];
for(let i = 0;i<nodeList.length;i++){
let index = nodes.indexOf(nodeList[i][0]) // 找到这一项,然后将其第二项插入到这一项的后面
nodes.splice(index+1,0,nodeList[i][1])
}
console.log(nodes.filter(v => v!= del).join(" "))
while(line = await readline()){
let tokens = line.split(' ');
let a = parseInt(tokens[0]);
let b = parseInt(tokens[1]);
}
}()
查看22道真题和解析
上海得物信息集团有限公司公司福利 1208人发布