Created
December 10, 2015 15:30
-
-
Save pdjota/f18b747c2b6d9bb709b9 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
//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