Last active
December 23, 2015 23:29
-
-
Save alnorris/6710436 to your computer and use it in GitHub Desktop.
Linked list in Javascript
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 node(data, next) { | |
this.data = data; | |
this.next = next; | |
} | |
function linkedlist() { | |
this.first = null; | |
} | |
linkedlist.prototype.insertNode = function(data) { | |
if(this.first == null) { | |
this.first = new node(data, null); | |
} else { | |
this.first = new node(data, this.first); | |
} | |
} | |
// print content of linkedlist in console.log | |
linkedlist.prototype.printlist = function() { | |
var temp = this.first; | |
while(temp != null) { | |
console.log(temp.data); | |
temp = temp.next; // switch temp to next node | |
} | |
} | |
linkedlist.prototype.reverse = function() { | |
var temp; | |
var previous = null; | |
while(this.first != null) { | |
temp = this.first.next; | |
this.first.next = previous; | |
previous = this.first; | |
this.first = temp; | |
} | |
this.first = previous; | |
} | |
// test it | |
var list = new linkedlist(); | |
list.insertNode("lol"); | |
list.insertNode("hey"); | |
list.insertNode("sup"); | |
list.insertNode("whahhta"); | |
list.printlist(); // prints to console.log |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment