Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
Basic Implementation
basic.py
stack = []
for value in [10, 20, 30]:
stack.append(value)
popped = []
while stack:
popped.append(stack.pop())
print(" -> ".join(str(x) for x in popped))
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- Python uses a plain list as the stack, with the right end as the top.
stack.append(value)mutates that list in place to push, andstack.pop()removes and returns the most recently pushed value. popped.append(stack.pop())transfers the returnedintreference into a separate output list while shrinking the stack. Both end operations are O(1) amortized for Python lists.- The persistent containers are just
stackandpopped; normal Python reference management owns their lifetime once no references remain. The trace shows[10, 20, 30]popping as30, then20, then10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.