Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Created March 30, 2017 06:12
Show Gist options
  • Save C-Rodg/572b90af7fdf8f74fe0d572f070526cb to your computer and use it in GitHub Desktop.
Save C-Rodg/572b90af7fdf8f74fe0d572f070526cb to your computer and use it in GitHub Desktop.
A Javascript implementation of a Doubly-Linked List.
function Node(value) {
this.data = value;
this.previous = null;
this.next = null;
}
function DoublyList() {
this._length = 0;
this.head = null;
this.tail = null;
}
DoublyList.prototype.add = function(data) {
let node = new Node(data);
if (this._length) {
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
} else {
this.head = node;
this.tail = node;
}
this._length += 1;
return node;
};
DoublyList.prototype.searchNodeAt = function(position) {
let currentNode = this.head,
length = this._length,
count = 1;
if (length === 0 || position < 1 || position > length) {
throw new Error("Non-existant node in this list");
}
while (count < position) {
currentNode = currentNode.next;
count += 1;
}
return currentNode;
};
DoublyList.prototype.remove = function(position) {
let currentNode = this.head,
length = this._length,
count = 1,
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null,
afterNodeToDelete = null;
if (length === 0 || position > length || position < 1) {
throw new Error("Non-existant node in this list");
}
if (position === 1) {
this.head = currentNode.next;
if (!this.head) {
this.head.previous = null;
} else {
this.tail = null;
}
} else if (position === this._length) {
this.tail = this.tail.previous;
this.tail.next = null;
} else {
while (count < position) {
currentNode = currentNode.next;
count++;
}
beforeNodeToDelete = currentNode.previous;
nodeToDelete = currentNode;
afterNodeToDelete = currentNode.next;
beforeNodeToDelete.next = afterNodeToDelete;
afterNodeToDelete.previous = beforeNodeToDelete;
deletedNode = nodeToDelete;
nodeToDelete = null;
}
this._length -= 1;
return "Node was removed";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment