Skip to content

Instantly share code, notes, and snippets.

@tucaz
Created July 5, 2011 00:03
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 tucaz/1064080 to your computer and use it in GitHub Desktop.
Save tucaz/1064080 to your computer and use it in GitHub Desktop.
Simple double linked list in javascript
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()));
@juanplopes
Copy link

Por que você adiciona métodos via prototype?

@tucaz
Copy link
Author

tucaz commented Jul 5, 2011

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