Skip to content

Instantly share code, notes, and snippets.

@fed
Last active August 22, 2017 18:48
Show Gist options
  • Save fed/16690d1723c16d79357a9b808d61b1dc to your computer and use it in GitHub Desktop.
Save fed/16690d1723c16d79357a9b808d61b1dc to your computer and use it in GitHub Desktop.
Singly-linked lists implementation
function Node(data) {
this.data = data;
this.next = null
}
function LinkedList() {
this.head = null;
this.length = 0;
}
LinkedList.prototype.add = function (data) {
const nodeToAdd = new Node(data);
let nodeToCheck = this.head;
if (!nodeToCheck) {
this.head = nodeToAdd;
this.length++;
return nodeToAdd;
}
while (nodeToCheck.next) {
nodeToCheck = nodeToCheck.next;
}
nodeToCheck.next = nodeToAdd;
this.length++;
return nodeToAdd;
};
LinkedList.prototype.get = function (num) {
let nodeToCheck = this.head;
let count = 0;
if (num > this.length) {
throw new Error(`The requested node doesn't exist`);
}
while(count < num) {
nodeToCheck = nodeToCheck.next;
count++;
}
return nodeToCheck;
}
LinkedList.prototype.remove = function (num) {
let nodeToCheck = this.head;
let length = this.length;
let count = 0;
let prevNode = null;
if (num > length) {
throw new Error(`The requested node doesn't exist`);
}
if (num === 0) {
this.head = nodeToCheck.next;
this.length--;
return this.head;
}
while (count < num) {
prevNode = nodeToCheck;
nodeToCheck = nodeToCheck.next;
count++;
}
prevNode.next = nodeToCheck.next;
nodeToCheck = null;
this.length--;
return this.head;
}
const list = new LinkedList();
list.add('first');
list.add('second');
list.add('third');
list.add('fourth');
try {
console.log(list.get(2));
console.log(list.get(7));
} catch(error) {
console.log('Error:', error.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment