美文网首页
手写双向链表,增加/移除/插入功能

手写双向链表,增加/移除/插入功能

作者: Time_Notes | 来源:发表于2020-07-09 01:33 被阅读0次

class DNode {

    constructor(val) {

      this.val = val;

      this.prev = null;

      this.next = null;

    }

}


添加
function add(el) {

  var currNode = this.head;

  while (currNode.next != null) {

    currNode = currNode.next;

  }

  var newNode = new DNode(el);

  newNode.next = currNode.next;

  currNode.next = newNode;

}


查找
function find(el) {

  var currNode = this.head;

  while (currNode && currNode.el != el) {

    currNode = currNode.next;

  }

  return currNode;

}


插入
function insert(newEl, oldEl) {

  var newNode = new DNode(newEl);

  var currNode = this.find(oldEl);

  if (currNode) {

    newNode.next = currNode.next;

    newNode.prev = currNode;

    currNode.next = newNode;

  } else {

    throw new Error('未找到指定要插入节点位置对应的值!')

  }

}


删除
function delete(el) {

  var currNode = this.find(el);

  if (currNode && currNode.next != null) {

    currNode.prev.next = currNode.next;

    currNode.next.prev = currNode.prev;

    currNode.next = null;

    currNode.previous = null;

  } else {

    throw new Error('找不到要删除对应的节点');

  }

}


// 顺序

function () {

  var currNode = this.head.next;

  while (currNode) {

    console.log(currNode.el);

    currNode = currNode.next;

  }

}

// 逆序

function () {

  var currNode = this.head;

  currNode = this.findLast();

  while (currNode.prev != null) {

    console(currNode.el);

    currNode = currNode.prev;

  }

}

相关文章

网友评论

      本文标题:手写双向链表,增加/移除/插入功能

      本文链接:https://www.haomeiwen.com/subject/doloqktx.html