Use a stack to reverse a word.
What to build
A program that shows why a stack reverses the order of things.
Requirements
- Push each character of the word onto a list.
- Pop them all off and join them into the result.
- Do not use slicing or
reversed.
Input
One word.
Output
The word backwards.
Constraints
The word has from 1 to 1000 characters.
Example
Input:
hello
Output:
olleh
Why it works
The last character pushed is the first popped, so emptying a stack gives its contents in reverse order.
Examples
Example 1 · Input
hello
Expected output
olleh
Example 2 · Input
a
Expected output
a
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Push each character with append.
Hint 2
Pop until the stack is empty.
Solution
Show one correct solution (try it yourself first)
word = input()
stack = []
for ch in word:
stack.append(ch)
result = ""
while stack:
result += stack.pop()
print(result)