Created
July 5, 2011 00:03
-
-
Save tucaz/1064080 to your computer and use it in GitHub Desktop.
Simple double linked list in 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
var Node = function (v) { | |
if ( !(this instanceof arguments.callee) ) { | |
throw new Error("Constructor called as a function"); | |
} | |
this.value = v; | |
this.next = null; | |
this.previous = null; | |
} | |
Node.prototype.setValue = function(v) { | |
this.value = v; | |
} | |
Node.prototype.getValue = function() { | |
return this.value; | |
} | |
Node.prototype.setNext = function(n) { | |
this.next = n; | |
} | |
Node.prototype.getNext = function() { | |
return this.next; | |
} | |
Node.prototype.setPrevious = function(p) { | |
this.previous = p; | |
} | |
Node.prototype.getPrevious = function() { | |
return this.previous; | |
} | |
var LinkedList = function () { | |
if ( !(this instanceof arguments.callee) ) { | |
throw new Error("Constructor called as a function"); | |
} | |
this.head = null; | |
this.tail = null; | |
} | |
LinkedList.prototype.add = function(value) | |
{ | |
var node = new Node(value); | |
if (this.head == null) { | |
this.head = node; | |
} | |
if (this.tail != null) { | |
this.tail.setNext(node); | |
node.setPrevious(this.tail); | |
} | |
this.tail = node; | |
} | |
LinkedList.prototype.insertAfter = function(node, value) | |
{ | |
var newNode = new Node(value); | |
for(var n = ll.head; n; n = n.getNext()) | |
{ | |
if(n.getValue() === node.getValue()) | |
{ | |
var nextNode = n.getNext(); | |
nextNode.setPrevious(newNode) | |
n.setNext(newNode); | |
newNode.setNext(nextNode); | |
newNode.setPrevious(n); | |
break; | |
} | |
} | |
} | |
var ll = new LinkedList(); | |
ll.add(1); | |
ll.add(2); | |
ll.add(4); | |
for(var n = ll.head; n; n = n.getNext()) | |
console.log('Value: '+ n.getValue() + ' | Previous: ' + (n.getPrevious() == null ? '' : n.getPrevious().getValue())); | |
ll.insertAfter(new Node(2), 3); | |
for(var n = ll.head; n; n = n.getNext()) | |
console.log('Value: '+ n.getValue() + ' | Previous: ' + (n.getPrevious() == null ? '' : n.getPrevious().getValue())); |
Geralmente eu escrevo usando object literal + closure pra manter props privadas, mas nesse caso eu queria que meus objetos tivessem uma "cara" de classe/esqueleto mesmo. Daria pra escrever de outro jeito, mas fiz desse jeito pra praticar tb :P
Ainda preciso colocar em um module e terminar de implementar uns metodos e ai coloco no GitHub. Algum comentário? :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Por que você adiciona métodos via prototype?