Created
February 4, 2014 05:39
-
-
Save aclave1/8798657 to your computer and use it in GitHub Desktop.
Simple Javascript Linked List
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
var LinkedList = function() { | |
var head, tail; | |
var Node = function(dat) { | |
var _node = this, | |
_next = null, | |
_previous = null, | |
_data = dat; | |
this.gotoHead = function() { | |
return head; | |
}; | |
this.gotoTail = function() { | |
return tail; | |
}; | |
this.setData = function(data) { | |
_data = data; | |
}; | |
this.getData = function() { | |
return _data; | |
}; | |
this.getPrev = function() { | |
return _previous; | |
}; | |
this.getNext = function() { | |
return _next; | |
}; | |
this.setNext = function(to) { | |
_next = to; | |
}; | |
this.setPrev = function(prev) { | |
_previous = prev; | |
}; | |
}; | |
head = new Node(); | |
tail = new Node(); | |
head.setPrev(tail); | |
tail.setNext(head); | |
this.add = function(data) { | |
var n = head.getNext(); | |
var p = head; //previous | |
while (n !== null) { | |
p = n; | |
n = n.getNext(); | |
} | |
n = new Node(data); | |
p.setNext(n); | |
n.setPrev(p); | |
}; | |
//get's the 0 based i'th node, returns null otherwise. | |
this.get = function(i) { | |
var count, | |
p, | |
n = head.getNext(); | |
while (n !== null) { | |
if (count == i) { //i wouldnt mind a string. | |
return n; | |
} | |
count++; | |
n = n.getNext(); | |
} | |
return null; | |
}; | |
this.iterate = function(iter) { | |
var n = head.getNext(); | |
while (n !== null) { | |
iter(n); | |
n = n.getNext(); | |
} | |
}; | |
//Applies the function iter to every node in the linked list's data attribute. | |
this.iterateData = function(iter) { | |
var n = head.getNext(); | |
while (n !== null) { | |
iter(n.getData()); | |
n = n.getNext(); | |
} | |
}; | |
}; | |
//Sample Usage | |
var LLIST = new LinkedList(); | |
LLIST.add('sup'); | |
LLIST.add('yo'); | |
LLIST.add({ | |
message: 'cool' | |
}); | |
LLIST.add(6); | |
// | |
LLIST.iterate( | |
function(node) { | |
console.log(node.getData()); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment