Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/b58399e36b9259880027813abd0c3647 to your computer and use it in GitHub Desktop.
Save dotproto/b58399e36b9259880027813abd0c3647 to your computer and use it in GitHub Desktop.
Linked List implementation that behaves like a stack (last in, first out)
const VOID = Symbol('VOID');
class LinkedItem {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this._length = 0;
this.head = undefined;
}
get length() {
return this._length;
}
push(value = VOID) {
const newHead = new LinkedItem(value);
newHead.next = this.head;
this.head = newHead;
return value !== VOID ? ++this._length : this._length;
}
pop() {
if (!this._length) return undefined;
--this._length;
const current = this.head;
this.head = this.head.next || undefined;
return current.value;
}
peak() {
return this._length ? this.head.value : undefined;
}
clear() {
this.head = undefined;
this._length = 0;
}
*[Symbol.iterator]() {
let current = this.head;
if (current === undefined) { return }
do {
yield current.value;
current = current.next;
} while (current)
}
toArray() {
return Array.from(this);
}
static fromIterable(it) {
const ll = new LinkedList();
for (let value of it) {
ll.push(value)
}
return ll;
}
static fromIterableReversed(it) {
const ll = new LinkedList();
const arr = Array.from(it);
for(let i = arr.length; i--; ) {
ll.push(arr[i])
}
return ll;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment