Created
June 6, 2013 15:15
-
-
Save wesleytodd/5722292 to your computer and use it in GitHub Desktop.
Linked List In Javascript
This file contains hidden or 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
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