Algorithmsstack state management
Stack State Management
TT
Testlaa Team
May 14, 2026•1 min read
Use a stack when your algorithm has explicit phases or scopes (branches, DFS frames, undo logs). Push on enter, pop on exit.
Try this in Python
def eval_rpn(tokens: list[str]) -> int:
st: list[int] = []
for t in tokens:
if t in "+-*":
b = st.pop()
a = st.pop()
if t == "+":
st.append(a + b)
elif t == "-":
st.append(a - b)
else:
st.append(a * b)
else:
st.append(int(t))
return st[-1]
print(eval_rpn(["2", "1", "+", "3", "*"]))
Key takeaways
- RPN is a tiny language of deferred operations—classic stack state.
- Each operator collapses the top two states into one.
- Think “what is waiting for more operands?”
Tags:
Stacks & queuesPythonStudents
