Skip to content

Instantly share code, notes, and snippets.

@ConnorAtherton
Last active August 29, 2015 13:57
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 ConnorAtherton/9841185 to your computer and use it in GitHub Desktop.
Save ConnorAtherton/9841185 to your computer and use it in GitHub Desktop.
JavaScript linked list implementation
// 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