Skip to content

Instantly share code, notes, and snippets.

@jpoechill
Created May 12, 2017 06:34
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 jpoechill/594bc69265e34ada6125d048adc93aa2 to your computer and use it in GitHub Desktop.
Save jpoechill/594bc69265e34ada6125d048adc93aa2 to your computer and use it in GitHub Desktop.
Linked Lists via. FEM
function Node (value) {
this.next = null;
this.value = value;
}
function LinkedList (headValue) {
if (headValue === undefined) console.log("Head must be defined");
this.head = new Node(headValue);
this.tail = this.head;
}
LinkedList.prototype.forEach = function (callback) {
var node = this.head;
while (node) {
callback(node.value);
node = node.next;
}
}
LinkedList.prototype.print = function () {
var result = [];
this.forEach(function (value) {
result.push(value);
});
return result.join(', ');
)
}
LinkedList.prototype.insertAfter = function(node, value) {
// get reference to former next
var oldNext = node.next;
// create new node
var newNext = new Node(value);
// store it as the new next
node.next = newNext;
// set next for the new node to old next
newNext.next = oldNext;
// if reference node is tail, set tail to newNext
if (this.tail === node) this.tail = newNext;
return newNext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment