Skip to content

Instantly share code, notes, and snippets.

@pdjota
Created December 10, 2015 15:30
Show Gist options
  • Save pdjota/f18b747c2b6d9bb709b9 to your computer and use it in GitHub Desktop.
Save pdjota/f18b747c2b6d9bb709b9 to your computer and use it in GitHub Desktop.
//Implementing a Linked List in JS
//Example:
//var a = new List([1,2,3,4]);
//at = a.reverse();
function List (initialArray) {
var list = this;
list.first = null;
if (!!initialArray) {
initialArray.forEach(function (elem) {
list.append(elem);
});
}
}
List.prototype.append = function (data) {
var list = this;
var node = { data:data, next:null };
if (!!list.first) {
var item = list.first;
while(item.next) {
item = item.next;//move to the end of the list.
}
item.next = node;
} else {
list.first = node;
}
}
List.prototype.toArray = function () {
var arr = [];
if (!!this.first) {
var item = this.first;
arr.push(item.data);
while (item.next) {
item = item.next;
arr.push(item.data);
}
}
return arr;
}
List.prototype.reverse = function () {
return new List(this.toArray().reverse());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment