Created
October 11, 2013 22:39
-
-
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!)
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 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