Created
May 12, 2017 06:34
-
-
Save jpoechill/594bc69265e34ada6125d048adc93aa2 to your computer and use it in GitHub Desktop.
Linked Lists via. FEM
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
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