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

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

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

全部评论

相关推荐

中电45所 测试开发岗 可以解决北京户口,提供员工宿舍,早 8 晚 5(不过一般会加班到7-8点,周六一般也会去,面试官说的) 硕士
点赞 评论 收藏
转发
投递华为等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务