4.3.3 Stack Example: Reverse a String
In this example, we are pushing letters into the stack. After loopin through the entire phrase and putting the letters in the stack, we then use a while loop to remove the letters.
Let’s walk through a simple example. Suppose the user entered the word hat
. Our for
loop will loop three times, first with the h
, then the a
, and finally the t
.
Here is what our stack would look like after each iterations:
Each time, the previous letter is pushed further down. In the stack, we only have access to the letter on the top, so as we move through the stack in our while
loop, we remove the letters in reverse order.
Notice how we access each letter in the stack with the top command and then remove the letter with the pop command. Once removed, this letter is lost, so there is no way to loop through and view each letter without removing it entirely from the stack.
Last updated