Skip to content

Instantly share code, notes, and snippets.

@L-A
Last active February 2, 2021 17:21
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 L-A/8ff34b8b2a9d636667af314892f777cb to your computer and use it in GitHub Desktop.
Save L-A/8ff34b8b2a9d636667af314892f777cb to your computer and use it in GitHub Desktop.
Javascript linked list class
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