Last active
August 29, 2015 13:57
-
-
Save ConnorAtherton/9841185 to your computer and use it in GitHub Desktop.
JavaScript linked list implementation
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
// TODO - Don't expose this, keep it internal to implementation | |
function Node(value, next) { | |
this.value = value; | |
this.next = next || null; | |
} | |
// TODO - Only expose this to global | |
function LinkedList() { | |
this.first = null; | |
this.last = null; | |
this.size = 0; | |
} | |
LinkedList.prototype.iterate = function(callback) { | |
var current = this.first; | |
while (current !== null) { | |
callback.call(this, current); | |
current = current.next; | |
} | |
} | |
LinkedList.prototype.append = function(value) { | |
var node = new Node(value); | |
if (this.size === 0) { | |
this.first = node; | |
} else { | |
this.last.next = node; | |
} | |
// node.next = null; | |
this.last = node; | |
this.size++; | |
return this; | |
} | |
function Iterator(list) { | |
this.list = list; | |
this.index = list.first; | |
} | |
Iterator.prototype.hasNext = function() { | |
return this.index !== null && this.index.next !== null; | |
} | |
Iterator.prototype.next = function() { | |
var nextNode = this.index.next; | |
this.index = nextNode; | |
return this.index; | |
} | |
var list = new LinkedList(); | |
list.append('first'); | |
list.append('second'); | |
list.append('third'); | |
var i = new Iterator(list); | |
while(i.hasNext()) { | |
i.next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment