Skip to content

Instantly share code, notes, and snippets.

@wesleytodd
Created June 6, 2013 15:15
Show Gist options
  • Save wesleytodd/5722292 to your computer and use it in GitHub Desktop.
Save wesleytodd/5722292 to your computer and use it in GitHub Desktop.
Linked List In Javascript
var LinkedList = function() {
this._head = null;
this._tail = null;
this.length = 0;
};
LinkedList.Node = function(data) {
return {
data : data,
next : null
};
};
LinkedList.prototype.append = function(data) {
var node = LinkedList.Node(data);
if (!this._head) {
this._head = node;
}
if (!this._tail) {
this._tail = node;
}
this._tail.next = node;
this._tail = node;
this.length++;
};
LinkedList.prototype.prepend = function(data) {
var node = LinkedList.Node(data);
node.next = this._head;
this._head = node;
if (!this._tail) {
this._tail = node;
}
this.length++;
};
LinkedList.prototype.remove = function(val) {
var last = null;
this.each(function(item) {
if (item.data == val) {
if (item == this._head) {
this._head = item.next;
}
if (item == this._tail) {
if (last) {
last.next = null;
this._tail = last;
} else {
this._tail = null;
}
}
if (last) {
last.next = item.next;
}
this.length--;
}
last = item;
});
};
LinkedList.prototype.each = function(fnc) {
if (this.length > 0) {
var head = this._head;
fnc.call(this, head);
while (head = head.next) {
if(fnc.call(this, head) === false) return;
}
}
};
LinkedList.prototype.get = function(val) {
var match;
this.each(function(item) {
if (item.data == val) {
match = item;
return false;
}
});
return match;
};
LinkedList.prototype.reverse = function() {
var extra,
prev = null;
while (this._head) {
extra = this._head.next;
this._head.next = prev;
prev = this._head;
this._head = extra;
}
this._head = prev;
};
LinkedList.prototype.sort = function() {
// @todo
};
LinkedList.merge(a, b) {
};
var l = new LinkedList();
l.prepend('1');
l.prepend('2');
l.prepend('3');
l.prepend('4');
l.reverse();
console.log(l);
l.each(function(item) {
console.log(item.data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment