Skip to content

Instantly share code, notes, and snippets.

@w8r
Created August 2, 2018 13:09
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 w8r/7aea48f9c1f32da4c4d369b047787cdc to your computer and use it in GitHub Desktop.
Save w8r/7aea48f9c1f32da4c4d369b047787cdc to your computer and use it in GitHub Desktop.
sibly linked list
export default class SinglyList {
constructor () {
this._length = 0;
this.head = null;
}
add (value) {
const newNode = new { data: value, next: null };
let current = this.head;
// 1st use-case: An empty list.
if (!current) {
this.head = newNode;
this._length++;
return newNode;
}
// 2nd use-case: An non empty list
newNode.next = current;
this.head = node;
this._length++;
return newNode;
}
at (position) {
let current = this.head;
const length = this._length;
let count = 1;
// 1st use-case: An invalid position
if (length === 0 || position < 0 || position > length) {
throw new Error(`Invalid position ${position}`);
}
// 2nd use-case: A valid position
while (count < position) {
current = current.next;
count++;
}
return current;
}
forEach (fn) {
let node = this.head;
while (node) {
fn(node);
node = node.next;
}
}
remove (position) {
let node = this.head;
const length = this._length;
let count = 0,
let prev = null;
let toRemove = null;
let removed = null;
// 1st use-case: an invalid position
if (position < 0 || position > length) {
throw new Error(`Invalid position ${position}`);
}
if (position === 0) {
this.head = node.next;
removed = node;
node = null;
this._length--;
return removed;
}
while (count < position) {
prev = node;
toRemove = node.next;
count++;
}
prev.next = toRemove.next;
removed = toRemove;
toRemove = null;
this._length--;
return removed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment