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

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

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

全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
湫湫湫不会java:先投着吧,大概率找不到实习,没实习的时候再加个项目,然后把个人评价和荣誉奖项删了,赶紧成为八股战神吧,没实习没学历,秋招机会估计不多,把握机会。或者说秋招时间去冲实习,春招冲offer,但是压力会比较大
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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