Stack Basics
Step 1 of 9
push / popO(1)reachable—
operations
+a
+b
+c
peek
pop
pop
stackempty
a
b
c
A stack is a pile with one open end. Everything happens at the top.
The Idea
A stack only lets you touch one end: the top. Push puts an item there, pop takes the newest one back off. Both are O(1) because nothing else in the pile moves. The price is that older items are buried until you clear what sits above them.
Real-World Example
A drawing app's undo history. Every stroke lands on top of the pile, and undo lifts off the most recent one. To get back to a sketch you made ten strokes ago, you have to undo the nine strokes drawn after it first.
The Code
Your turn
What does this print?
s = []
for ch in "SUN":
s.append(ch)
print(s.pop() + s.pop())Mini quiz
1 / 3