Skip to content

Instantly share code, notes, and snippets.

@GrantSchiller
Last active December 24, 2015 07:28
Show Gist options
  • Save GrantSchiller/6763526 to your computer and use it in GitHub Desktop.
Save GrantSchiller/6763526 to your computer and use it in GitHub Desktop.
Stack Runner
/*
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?
}
@cangevine
Copy link

#36: Nice implementation -- and thank you for citing your "source"!
#44: Beautiful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment