Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Last active April 4, 2017 19:27
Show Gist options
  • Save C-Rodg/5710804c659888f98bf130093c9c5b57 to your computer and use it in GitHub Desktop.
Save C-Rodg/5710804c659888f98bf130093c9c5b57 to your computer and use it in GitHub Desktop.
A Javascript implementation of a Singly-Linked List
function Node(data) {
this.data = data;
this.next = null;
}
function SinglyList() {
this._length = 0;
this.head = null;
}
SinglyList.prototype.add = function(value) {
let node = new Node(value),
currentNode = this.head;
if (!currentNode) {
this.head = node;
this._length += 1;
return node;
}
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length += 1;
return node;
};
SinglyList.prototype.searchNodeAt = function(position) {
let currentNode = this.head,
length = this._length,
count = 1;
if (length === 0 || position < 1 || position > length) {
throw new Error("Non-existent node in this list");
}
while (count < position) {
currentNode = currentNode.next;
count++;
}
return currentNode;
};
SinglyList.prototype.remove = function(position) {
let currentNode = this.head,
length = this._length,
count = 1,
beforeNodeToDelete = null,
deletedNode = null;
if (position < 0 || position > length || length === 0) {
throw new Error("Non-existent node in list");
}
if (position === 1) {
this.head = currentNode.next;
deletedNode = currentNode;
currentNode = null;
this._length -= 1;
return deletedNode;
}
while (count < position) {
beforeNodeToDelete = currentNode;
currentNode = currentNode.next;
count++;
}
beforeNodeToDelete.next = currentNode.next;
deletedNode = currentNode;
currentNode = null;
this._length -= 1;
return deletedNode;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment