Last active
August 29, 2015 14:07
-
-
Save vegarnorman/c51d560d6b66099eb5d4 to your computer and use it in GitHub Desktop.
A simple LinkedList implementation using JavaScript
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
LinkedListItem.prototype = { | |
getId: function() { return this.id; }, | |
getNext: function() { return (this.next !== undefined || null) ? this.next : null; }, | |
setNext: function(next) { this.next = next; }, | |
unsetNext: function() { delete this.next; }, | |
getPrev: function() { return this.prev; }, | |
isLast: function() { return (this.next === undefined || this.next === null) ? true : false; }, | |
isFirst: function() { return this.isInitial; }, | |
getContent: function() { return this.content; }, | |
setContent: function(content) { this.content = content; } | |
} | |
LinkedList.prototype = { | |
getFirst: function() { return this.initialNode; }, | |
getLast: function() { | |
var node = this.getFirst(); | |
if (node.getNext() === null) return node; | |
while (node.getNext() !== null) node = node.getNext(); | |
return node; | |
}, | |
addItem: function(content) { | |
if (this.getFirst() === null) { | |
this.initialNode = new LinkedListItem(content, true, this.length, undefined); | |
return; | |
} | |
var node = this.getLast(); | |
node.setNext(new LinkedListItem(content, false, this.length, node)); | |
this.length++; | |
}, | |
findItem: function(id) { | |
var node = this.getFirst(); | |
if (node.id === id) return node; | |
while (node.getNext() !== null) { | |
node = node.getNext(); | |
if (node.id === id) return node; | |
} | |
return undefined; | |
} | |
} | |
function LinkedList() { | |
this.initialNode = null; | |
this.length = 0; | |
} | |
function LinkedListItem(content, isInitial, id, previous) { | |
this.content = content; | |
this.isInitial = isInitial; | |
this.id = id; | |
this.prev = previous; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment