Data Structures · Stack

Exercise: Reverse a String Using a Stack

Write a C++ program that takes a string from the user and uses a stack to reverse it. (Input: Hello → Output: olleH)

📥 Input string s

cout output:
character being processed pushed onto the stack popped / printed

📚 The stack stack<char>

↑ top
push / pop only here
bottom
(the first pushed sits lowest)
A stack is Last-In-First-Out (LIFO). The first character pushed is buried at the bottom, the last one sits on top — so popping gives the input in reverse order.

💬 Current step

💻 The C++ program

Yellow = current line. The four steps match the slide's "What You Should Do".

✅ What You Should Do

1Take a string input from the user.
2Push each character onto a stack.
3Pop characters from the stack and append them to a new string.
4Print the reversed string.
Why does a stack reverse the string? Push order = original order; pop order = the reverse of push order → appending the popped characters gives the reversed string.
Complexity: each character is pushed once and popped once → O(n) time, plus one stack → O(n) space.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result