Skip to content

Instantly share code, notes, and snippets.

@alnorris
Last active December 23, 2015 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alnorris/6710436 to your computer and use it in GitHub Desktop.
Save alnorris/6710436 to your computer and use it in GitHub Desktop.
Linked list in Javascript
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