Last active
February 2, 2021 17:21
-
-
Save L-A/8ff34b8b2a9d636667af314892f777cb to your computer and use it in GitHub Desktop.
Javascript linked list class
This file contains hidden or 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 LinkedList { | |
constructor(initialElement) { | |
this.length = 1; | |
this.head = initialElement; | |
this.head.next = this.head; | |
this.head.prev = this.head; | |
} | |
// Just to be nice. | |
value() { | |
return this.head; | |
} | |
addAfter(element) { | |
this.head.next.prev = element; | |
element.prev = this.head; | |
element.next = this.head.next; | |
this.head.next = element; | |
this.length++; | |
} | |
addBefore(element) { | |
this.head.prev.next = element; | |
element.prev = this.head.prev; | |
element.next = this.head; | |
this.head.prev = element; | |
this.length++; | |
} | |
delete(shiftForward = false) { | |
// Guard clause: No 0-length list! | |
if (this.length == 1) return; | |
let removed = this.head; | |
removed.prev.next = removed.next; | |
removed.next.prev = removed.prev; | |
if (shiftForward) this.head = removed.prev; | |
else this.head = removed.next; | |
removed = null; | |
this.length--; | |
} | |
next(count = 1) { | |
while (count-- > 0) this.head = this.head.next; | |
} | |
prev(count = 1) { | |
while (count-- > 0) this.head = this.head.prev; | |
} | |
} | |
export default LinkedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment