Created
August 17, 2013 09:56
-
-
Save jineeshjohn/6256168 to your computer and use it in GitHub Desktop.
JavaScript LinkedList Improved
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function LinkedList(){ | |
this.head = null; // can be replaced with class or model (to have strong type) | |
this.tail = null; | |
var count = 0; | |
this.AddFirst = function(node){ | |
//Save off the head node so we dont lose it | |
var temp = this.head; | |
//Point head to the new node | |
this.head = node; | |
//Insert the rest of the list behind the head | |
this.head.next = temp; | |
count++; | |
if( count == 1){ | |
this.tail = this.head; | |
} | |
}; | |
this.AddLast = function( node ){ | |
if( this.tail ){ // Set the previous node with current | |
this.tail.next = node; | |
}else{ // first time to set the pointer to head | |
this.head = node; | |
} | |
//Reset to the current node | |
this.tail = node; | |
}; | |
this.removeFirst = function(){ | |
if( this.head ){ | |
this.head = this.head.next; | |
} | |
}; | |
this.removeLast = function(){ | |
var current = this.head; | |
while( current.next != this.tail ){ | |
current = current.next; | |
} | |
current.next = null; | |
this.tail = current; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment