Skip to content

Instantly share code, notes, and snippets.

@lilywang711
Last active October 26, 2020 09:33
Show Gist options
  • Save lilywang711/52cdefb3c1446ef59a82690c75f6514a to your computer and use it in GitHub Desktop.
Save lilywang711/52cdefb3c1446ef59a82690c75f6514a to your computer and use it in GitHub Desktop.
class LinkedListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
const head = Symbol("linked list's head");
class LinkedList {
constructor() {
this[head] = null;
}
size() {
let count = 0;
let current = this[head];
while (current) {
current = current.next;
count++;
}
return count;
}
add(value) {
let lastNode = this[head];
let newNode = new LinkedListNode(value);
if (lastNode === null) {
return (this[head] = newNode);
}
while (lastNode.next) {
lastNode = lastNode.next;
}
lastNode.next = newNode;
}
remove(index) {
if (index < 0 || this[head] === null) {
throw new RangeError(`Index ${index} does not exist in the list.`);
}
if (index === 0) {
this[head] = this[head].next;
}
let i = 0;
let current = this[head];
let previous = null;
while (current && i < index) {
previous = current;
current = current.next;
i++;
}
if (current) {
previous.next = current.next;
return current.value;
}
throw new RangeError(`Index ${index} does not exist in the list.`);
}
get(index) {
if (index < 0) return undefined;
let i = 0;
let current = this[head];
while (current && i < index) {
current = current.next;
i++;
}
return current !== null ? current.value : undefined;
}
clear() {
this[head] = null;
return true;
}
*values() {
let current = this[head];
while (current !== null) {
yield current.value;
current = current.next;
}
}
[Symbol.iterator]() {
return this.values();
}
}
let linkedList = new LinkedList();
linkedList.add(0);
linkedList.add(1);
linkedList.add(2);
console.log("remove", linkedList.remove(1));
console.log('size', linkedList.size());
console.log([...linkedList])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment