javaScript双向链表

function ListNode(val) {
  this.val = val;
  this.next = null;
  this.prev = null;
}

class doubleLinkList {
  constructor() {
    this.length = 0;
    // 头部指针
    this.head = null;
    // 尾部指针
    this.last = null;
  }
  createNode(value) {
    return new ListNode(value);
  }

  append(value) {
    const newNode = this.createNode(value);
    if (!this.head) {
      // 是第一个列表元素
      this.head = newNode;
      this.last = newNode;
    } else {
      // 不是第一个元素,添加到列表末尾
      this.last.next = newNode;
      newNode.prev = this.last;
      this.last = newNode;
    }
    this.length++;
  }
  insert(value, index) {
    const newNode = this.createNode(value);
    if (index === 0) {
      // 在头部插入
      newNode.next = this.head;
      this.head.prev = newNode;
      this.head = newNode;
    } else if (index === this.length) {
      // 在尾部插入
      this.last.next = newNode;
      newNode.prev = this.last;
      this.last = newNode;
    } else {
      // 在中间位置插入
      let node = this.find(index);
      node.prev.next = newNode;
      newNode.prev = node.prev;

      newNode.next = node;
      node.prev = newNode;
    }
    this.length++;
  }
  find(index) {
    let current = this.head;
    if (index > this.length) {
      return new Error("out of range");
    } else if (index === 0) {
      return this.head;
    } else if (index === this.length) {
      return this.last;
    }
    while (index > 0 && index < this.length) {
      current = current.next;
      index--;
    }
    return current;
  }
  delete(index) {
    let node = this.find(index);
    if (index === this.length - 1) {
      this.last = node.prev;
      node.prev.next = null;
    } else if (index === 0) {
      this.head = node.prev;
      node.next.prev = null;
    } else {
      node.prev.next = node.next;
      node.next.prev = node.prev;
    }
    node.next = null;
    node.prev = null;
    this.length--;
  }
  displayList() {
    let current = this.head;
    while (current.next) {
      console.log(current);
      current = current.next;
    }
  }
}

const list = new doubleLinkList();
list.append({ name: "我是一" });
list.append({ name: "我是小马" });
list.append({ name: "我是小鸡" });

list.insert({ name: "小插" }, 2);

list.displayList();
list.delete(3);
console.log(list.length);
console.log(list.find(2));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值