JS版数据结构-链表

链表代码随笔(JS)

复制代码
/** 链表节点 */
class Node {
  el = null;
  next = null;

  constructor(el = null, next = null) {
    this.el = el;
    this.next = next;
  }
}

/** 链表 */
class LinkedList {
  #dummy = null;
  #size = 0;

  constructor() {
    this.#dummy = new Node();
  }

  getSize() {
    return this.#size;
  }

  isEmpty() {
    return this.#size === 0;
  }

  insert(idx, el) {
    if (idx < 0 || idx > this.#size) {
      throw new Error('Out of bounds!');
    }
    let prev = this.#dummy;
    for (let i = 0; i < idx; i++) {
      prev = prev.next;
    }
    prev.next = new Node(el, prev.next);
    this.#size++;
  }

  addFirst(el) {
    this.insert(0, el);
  }

  addLast(el) {
    this.insert(this.#size, el);
  }

  get(idx) {
    if (idx < 0 || idx >= this.#size) {
      throw new Error('Out of bounds!');
    }
    let cur = this.#dummy.next;
    for (let i = 0; i < idx; i++) {
      cur = cur.next;
    }
    return cur.el;
  }

  getFirst() {
    return this.get(0);
  }

  getLast() {
    return this.get(this.#size - 1);
  }

  set(idx, el) {
    if (idx < 0 || idx >= this.#size) {
      throw new Error('Out of bounds!');
    }
    let cur = this.#dummy.next;
    for (let i = 0; i < idx; i++) {
      cur = cur.next;
    }
    cur.el = el;
  }

  removeByIndex(idx) {
    if (idx < 0 || idx >= this.#size) {
      throw new Error('Out of bounds!');
    }
    let prev = this.#dummy;
    for (let i = 0; i < idx; i++) {
      prev = prev.next;
    }
    const target = prev.next;
    prev.next = target.next;
    target.next = null;
    this.#size--;

    return target;
  }

  contains(el) {
    let cur = this.#dummy.next;
    while (cur !== null) {
      if (cur.el === el) {
        return true;
      }
      cur = cur.next;
    }
    return false;
  }

  print() {
    let cur = this.#dummy;
    console.info('start: ' );
    while (cur !== null) {
      console.log(cur.el);
      cur = cur.next;
    }
    console.info('end!');
  }
}

const linkedList = new LinkedList();
linkedList.addLast(new Node(1))
linkedList.addLast(new Node(2))

linkedList.print();
复制代码

 

posted @   樊顺  阅读(76)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示