链表代码随笔(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();