Skip to content

Instantly share code, notes, and snippets.

@cangevine
Created October 1, 2013 15:36
Show Gist options
  • Save cangevine/6780382 to your computer and use it in GitHub Desktop.
Save cangevine/6780382 to your computer and use it in GitHub Desktop.
Stack.prototype.getLength = function() {
if (this.top == null) {
// If the Stack is empty, return 0
return 0;
} else {
// Otherwise start at the top, and begin counting at 1
var n = this.top;
var len = 1;
// Every time we call getNextNode() and get a Node object back (instead of null)...
while (n.getNextNode() != null) {
// increase the counter
len++;
// and update the value of n to progress to the next node.
// Without this line, we would hit an infinite loop always checking if the top Node has a next node.
n = n.getNextNode();
}
// Finally return the length that we've counted up to
return len;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment