Created
August 11, 2022 14:58
-
-
Save sebinsua/d0d15ad44b721d5210a6dc1dd3a1bf7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
Can we efficiently access nodes from the middle of the list? Can we efficiently insert, delete or update nodes in the middle of the list?
See: https://codesandbox.io/s/admiring-chandrasekhar-xggjxi?file=%2Fsrc%2Findex.js%3A0-6223