Last active
April 25, 2017 19:13
-
-
Save binary10ve/42a90d248b6768d2db7a53e0fa8d71e2 to your computer and use it in GitHub Desktop.
This file contains 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; | |
} | |
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); | |
} | |
Author
binary10ve
commented
Apr 25, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment