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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章