Easy Push/Pop All Stacks & Queues
In plain English: Reverse a string by pushing all characters onto a stack and popping them off.
LIFO order naturally reverses a sequence — push in order, pop gives reverse order.
Prompt
Reverse a string using a stack.
Try to write it from scratch before scrolling down.
Solution
def reverse_string(s):
stack = list(s) # push all chars
result = []
while stack:
result.append(stack.pop()) # LIFO pops in reverse order
return ''.join(result)
# Test: reverse_string("hello") == "olleh"