Skip to content

Instantly share code, notes, and snippets.

@binary10ve
Last active April 25, 2017 19:13
Show Gist options
  • Save binary10ve/42a90d248b6768d2db7a53e0fa8d71e2 to your computer and use it in GitHub Desktop.
Save binary10ve/42a90d248b6768d2db7a53e0fa8d71e2 to your computer and use it in GitHub Desktop.
function LinkedList(){
this.head = null;
}
LinkedList.prototype.append = function(data){
var newNode = {
data : data,
next : this.head // Since the new node is going to be the head, assigning existing head reference to next property
}
this.head = newNode;
}
LinkedList.prototype.prepend = function(x){
var newNode = {
data : x,
next : null // Since its a last node, next value will always be null
}
// If its a empty list, set the head value as new node and return
if(this.head == null){
this.head = newNode;
return;
}
// traverse throught the list till the last node is reached.
// to begin with traversing set the current as this.head which is nothing but the first element in the list;
var current = this.head;
// if current.next is null, it means loop has reached the last element and current is the last element.
while(current.next != null){
current = current.next;
}
// Assign the current.next to newNode
current.next = newNode;
}
LinkedList.prototype.print = function(){
var arr = [];
var current = this.head;
while(current !== null){
arr.push(current.data)
current = current.next;
}
console.log("LinkedList values : ", arr);
}
@binary10ve
Copy link
Author

headoflist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment