Skip to content

Instantly share code, notes, and snippets.

@ggilder
Created August 1, 2012 07:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ggilder/3224560 to your computer and use it in GitHub Desktop.
Save ggilder/3224560 to your computer and use it in GitHub Desktop.
Linked List Javascript implementation (node.js)
var assert = require('assert');
var LinkedStack = (function(){
function Item(data){
this.data = data;
this.next = null;
}
Item.prototype = {
tail: function(){
return this.next ? this.next : this;
}
};
function LinkedStack(){
this.head = null;
}
LinkedStack.prototype = {
push: function(data){
var oldHead = this.head;
this.head = new Item(data);
this.head.next = oldHead;
},
pop: function(){
if (this.head){
var popped = this.head;
this.head = popped.next;
return popped.data;
} else {
return null;
}
},
tail: function(){
if (this.head){
return this.head.tail().data;
} else {
return null;
}
}
};
return LinkedStack;
})();
describe('LinkedStack', function(){
var stack;
beforeEach(function(){
stack = new LinkedStack();
});
describe('#head', function(){
it('should return null for an empty stack', function(){
assert.equal(null, stack.head);
});
});
describe('#push', function(){
it('should push an item onto the top of the stack', function(){
stack.push('Hello');
assert.equal('Hello', stack.head.data);
stack.push('Hi');
assert.equal('Hi', stack.head.data);
});
});
describe('#pop', function(){
it('should return null on an empty stack', function(){
assert.equal(null, stack.pop());
});
it('should remove and return the top item on the stack', function(){
stack.push('Hello');
stack.push('Hi');
assert.equal('Hi', stack.pop());
assert.equal('Hello', stack.head.data);
});
});
describe('#tail', function(){
it('should return null for an empty stack', function(){
assert.equal(null, stack.tail());
});
it('should return the last item in the stack', function(){
stack.push('Hi');
stack.push('Buddy');
assert.equal('Hi', stack.tail());
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment