Skip to content

Instantly share code, notes, and snippets.

@dineshrajpurohit
Last active August 29, 2015 14:05
Show Gist options
  • Save dineshrajpurohit/1a56595bfcd38ba6552b to your computer and use it in GitHub Desktop.
Save dineshrajpurohit/1a56595bfcd38ba6552b to your computer and use it in GitHub Desktop.
Doubly Linked list implementation using Javascript
/**
* Javascript implementation of Doubly Linked list
*
* Dinesh
*
* (More to come) (Add more error handling scenarios)
*/
// Global object (namespace)
DS = {};
/**
* DList Nodes
*
*/
DS.DListNode = function(){
this.item = null;
this.next = null;
this.prev = null;
}
/**
* DLinkedList object
*/
DS.DLinkedList = function(){
this.head = null;
this.tail = null;
var size = 0;
//Insert Nodes
this.insertNode = function(item){
var node = new DS.DListNode();
node.item = item;
if(this.head == null){
this.head = node;
this.tail = node;
this.tail.next = null;
this.tail.prev = null;
size += 1;
}else{
var prev = this.tail;
this.tail.next = node;
this.tail = node;
this.tail.prev = prev;
size += 1;
}
}
//Insert node in the first location
this.insertFirst = function(item){
var node = new DS.DListNode();
node.item = item;
node.next = this.head;
this.head.prev = node;
this.head = node;
size += 1;
}
// Delete First node
this.deleteFirstNode = function(){
if(this.head != null){
this.head = this.head.next;
this.head.prev = null;
size -= 1;
}else{
console.log("Linked list is empty");
}
}
// Print Nodes
this.printNodes = function(){
if(size < 1) console.log("No node present in the Doubly Linked List");
var current = this.head;
for(var i=0;i<size;i++){
if(current.prev == null)
console.log("Node " + current.item + " is at location " + i + " : Previous Node: null : Next Node: "+current.next.item);
else if(current.next == null)
console.log("Node " + current.item + " is at location " + i + " : Previous Node: "+current.prev.item + " : Next Node: null");
else console.log("Node " + current.item + " is at location " + i + " : Previous Node: "+current.prev.item + " : Next Node: "+current.next.item);
current = current.next;
}
}
// Get node Size
this.getSize = function(){
return size;
}
}
var list = new DS.DLinkedList();
list.insertNode("test1");
list.insertNode("test2");
list.insertNode("test3");
list.insertNode("test4");
list.insertNode("test5");
list.insertNode("test6");
list.printNodes();
console.log("Adding item in the start");
list.insertFirst("test1st");
list.printNodes();
console.log("Deleting first node");
list.deleteFirstNode();
list.printNodes();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment