Skip to content

Instantly share code, notes, and snippets.

@esommer
Created October 11, 2013 22:39
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 esommer/6943089 to your computer and use it in GitHub Desktop.
Save esommer/6943089 to your computer and use it in GitHub Desktop.
Implementation of a stack and cheaty stack in JavaScript. (NOTE: I stupidly deleted my testing code... I need to rewrite it (better) and put it back in. Apologies!)
var assert = require("assert"); // node needs this module
// CHEATING STACK (using built-in functions):
function CheatingStack () {
this.contents = [];
}
CheatingStack.prototype.push = function (item) {
this.contents.push(item);
};
CheatingStack.prototype.pop = function () {
return this.contents.pop();
}
CheatingStack.prototype.isEmpty = function () {
return (this.contents.length === 0);
}
// STACK using only objects:
function Item (value, prevItem) {
this.value = value;
this.prevItem = prevItem;
}
function LinkedListStack () {
this.head = null;
}
LinkedListStack.prototype.push = function (item) {
var newItem = new Item (item, this.head);
this.head = newItem;
};
LinkedListStack.prototype.pop = function() {
if (this.isEmpty()) {
return false;
}
else {
var returnItem = this.head;
this.head = returnItem.prevItem;
return returnItem.value;
}
}
LinkedListStack.prototype.isEmpty = function() {
return (this.head === null);
}
// CLIENT CODE: testing our implementation
var myStack = new LinkedListStack();
// Yes... I deleted my testing code because it was imperfect. Yes, I need to rewrite it and put it back in. Perhaps after I finish writing about what I just learned!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment