Last active
December 24, 2015 07:28
-
-
Save GrantSchiller/6763526 to your computer and use it in GitHub Desktop.
Stack Runner
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
/* | |
Last in, first out linked list. | |
Stack | |
- top | |
+ push | |
+ pop | |
+ peek | |
+ getLength | |
+ isEmpty | |
*/ | |
function Stack() { | |
this.top = null; | |
} | |
Stack.prototype.push = function(n) { | |
n.setNextNode(this.top); | |
this.top = n; | |
} | |
Stack.prototype.pop = function() { | |
if(this.top != null) { | |
var n = this.top; | |
this.top = n.getNextNode(); | |
return n; | |
} | |
} | |
Stack.prototype.peek = function() { | |
return this.top; | |
} | |
Stack.prototype.getLength = function() { | |
var n = this.top; | |
var len = 0; | |
while(n != null) { // Thanks to Gianluca for recommending that I change to this from if-else. | |
n = n.getNextNode(); | |
len++; | |
} | |
return len; | |
} | |
Stack.prototype.isEmpty = function() { | |
return (this.top == null); // Better than a conditional, right? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#36: Nice implementation -- and thank you for citing your "source"!
#44: Beautiful!