Before you started coding, you should have tried to think about this problem visually. It would probably help to actually make a stack and then an empty helper stack and think about how you can move elements around until one of the stacks contains all the elements in sorted order.
Here is an explanation of how the solution works– this is just an explanation of the algorithm and contains no code (at one point the video says that 8 is smaller than 2 instead of 8 is bigger than 2 but the solution is still correct):
(click on the image to be taken to the video)
The general idea is that you always pop the top element of the stack which you are sorting. You want to add this to the helper stack but first need to make sure that doing so won't make the helper stack unsorted.
When all elements from the original stack are in the helper stack (i.e. the original stack is empty), you need to assign the original stack to the sorted helper stack. Doing this can be a little confusing but remember that the Stack data structure only has knowledge of its top element. Each element then has a link/pointer to the element below it.So all we have ot do is assign the top of the original stack to the top of the sorted helper stack and we will be finished.
Here is one Javascript solution to this problem:
Stack.prototype.sort = function() {
var helperStack = new Stack();
while (!this.isEmpty()) {
var curr = this.pop();
while (!helperStack.isEmpty() && helperStack.peek() > curr) {
this.push(helperStack.pop());
}
helperStack.push(curr);
}
this.top = helperStack.top;
};