Javascript Data Structure Implementation : Singly LinkedList

This program demonstrates the link list implementation in Javascript. The Insert, Delete, Search Operation has been implemented.

Find the Javascript Code below :

// Class representing the node
function Node(data) {
this.data = data;
this.next = null;
}

// Class representing the SinglyLinkedList
function SinglyList() {
this._length = 0;
this.head = null;
}

// Function to add the new node into the list
SinglyList.prototype.add = function(value) {
var node = new Node(value),
currentNode = this.head;

// 1st use-case: an empty list
if (!currentNode) {
this.head = node;
this._length++;

return node;
}

// 2nd use-case: a non-empty list
while (currentNode.next) {
currentNode = currentNode.next;
}

currentNode.next = node;

this._length++;

return node;
};

// Function to search the node in list
SinglyList.prototype.searchNodeAt = function(position) {
var currentNode = this.head,
length = this._length,
count = 1,
message = {failure: 'Failure: non-existent node in this list.'};

// 1st use-case: an invalid position
if (length === 0 || position length) {
throw new Error(message.failure);
}

// 2nd use-case: a valid position
while (count < position) {
currentNode = currentNode.next;
count++;
}

return currentNode;
};

// Function to remove element from the list
SinglyList.prototype.remove = function(position) {
var currentNode = this.head,
length = this._length,
count = 0,
message = {failure: 'Failure: non-existent node in this list.'},
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null;

// 1st use-case: an invalid position
if (position length) {
throw new Error(message.failure);
}

// 2nd use-case: the first node is removed
if (position === 1) {
this.head = currentNode.next;
deletedNode = currentNode;
currentNode = null;
this._length--;

return deletedNode;
}

// 3rd use-case: any other node is removed
while (count < position) {
beforeNodeToDelete = currentNode;
nodeToDelete = currentNode.next;
count++;
}

beforeNodeToDelete.next = nodeToDelete.next;
deletedNode = nodeToDelete;
nodeToDelete = null;
this._length--;

return deletedNode;
};

Any suggestion is invited if any.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s