Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created August 11, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/d0d15ad44b721d5210a6dc1dd3a1bf7e to your computer and use it in GitHub Desktop.
Save sebinsua/d0d15ad44b721d5210a6dc1dd3a1bf7e to your computer and use it in GitHub Desktop.
class DoublyLinkedListNode {
constructor(value) {
this.value = value;
this.head = null;
this.tail = null;
}
valueOf() {
return this.value;
}
}
class DoublyLinkedList {
constructor(values = []) {
this.head = null;
this.tail = null;
this.length = 0;
for (const value of values) {
this.push(value);
}
}
unshift(value) {
const node = new DoublyLinkedListNode(value);
if (!this.head) {
this.head = node;
this.tail = node;
return;
}
const currentHead = this.head;
currentHead.head = node;
node.tail = currentHead;
this.head = node;
this.length++;
}
shift() {
const currentHead = this.head;
const value = currentHead ? currentHead.value : null;
const newHead = currentHead.tail;
newHead.head = null;
this.head = newHead;
this.length--;
return value;
}
push(value) {
const node = new DoublyLinkedListNode(value);
if (!this.tail) {
this.head = node;
this.tail = node;
this.length++;
return;
}
const currentTail = this.tail;
currentTail.tail = node;
node.head = currentTail;
this.tail = node;
this.length++;
}
pop() {
if (!this.tail) {
return null;
}
const currentTail = this.tail;
const value = currentTail.value;
const previousNode = currentTail.head;
previousNode.tail = null;
this.tail = previousNode;
this.length--;
return value;
}
*[Symbol.iterator]() {
let currentNode = this.head;
if (!currentNode) {
return;
}
while (currentNode) {
yield currentNode.value;
currentNode = currentNode.tail;
}
}
}
const list = new DoublyLinkedList();
list.push(1);
list.push(2);
list.push(3);
list.pop();
for (let v of list) {
console.log(v);
}
console.log(list);
@sebinsua
Copy link
Author

sebinsua commented Aug 11, 2022

Can this be made faster at seeking/peeking at a node when given a key/value by adding a Map to this? What about duplicates? Do we key by value or create an additional key?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment