Quick Answer
Stack data structure follows last in first out. You push items on top and pop items from the top. This post shows 3 ways to build one. They are a Python list, linked nodes and the C++ stack class. All stack operations take O(1) time. Space is O(n). Python and C++ code below was executed.
Pile of plates is a stack. You add a plate to the top and you take a plate from the top. Nobody pulls one from the middle.
That single habit is the entire idea. Once it clicks a surprising amount of computing makes more sense.
What Is a Stack Data Structure?
Stack data structure means a collection where you only touch the top. You add to the top and you remove from the top. Items in the middle are out of reach until you clear what sits above them.
This rule is called last in first out or LIFO. Newest item always comes off first. Arrays let you reach any spot directly while every stack data structure gives up that freedom for order.
See the stack lesson for a short reference and the what is DSA guide for the wider path.
How Does a Stack Work Step by Step?
Start with an empty stack. Push 3 and the stack is 3.
Push 7 and it sits on top so the stack is 3 then 7. Push 1 and the top is 1.
Pop once. Value 1 comes off and 7 is the top again. Pop again. Value 7 comes off and only 3 remains.
Items came off in the order 1 then 7. That is the reverse of the order they went in. Reversal is the signature of a stack data structure.
What Are the Main Stack Operations?
- Push. Adds an item to the top.
- Pop. Removes the top item and returns it.
- Peek. Shows the top item without removing it.
- isEmpty. Checks whether any items remain.
Popping an empty stack is an error called stack underflow. Check isEmpty before every pop.
How Do You Code a Stack Data Structure in Python and C++?
Examples below push 3, 7 and 1 and then pop. Every version gives the same order.
Approach #1: Python List
What you get. Shortest code. Lists already add and remove at their end.
class Stack:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def pop(self):
if self.is_empty():
return None
return self.items.pop()
def peek(self):
if self.is_empty():
return None
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
stack = Stack()
for value in (3, 7, 1):
stack.push(value)
print("push", value, "top", stack.peek())
print("pop", stack.pop(), "top", stack.peek())
print("pop", stack.pop(), "top", stack.peek())
print(stack.is_empty())
Output shows the top after every push. Pops return 1 and then 7 and the final line is False because 3 remains.
Approach #2: Linked Nodes
What you get. Stack with no resizing. Every node points to the node below it.
class Node:
def __init__(self, value, below):
self.value = value
self.below = below
class LinkedStack:
def __init__(self):
self.top = None
def push(self, value):
self.top = Node(value, self.top)
def pop(self):
if self.top is None:
return None
value = self.top.value
self.top = self.top.below
return value
def peek(self):
return None if self.top is None else self.top.value
def is_empty(self):
return self.top is None
stack = LinkedStack()
for value in (3, 7, 1):
stack.push(value)
print(stack.pop(), stack.pop(), stack.pop(), stack.pop())
Output is 1 7 3 None. Fourth pop returns None because the stack is empty.
Approach #3: C++ Stack Class
What you get. Ready made stack from the standard library. Include <stack> and call the same operations.
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(3);
s.push(7);
s.push(1);
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.empty() << endl;
}
Output is 1 then 7 then 3 then 1. Last 1 means empty() returned true. Calling top or pop on an empty C++ stack is undefined behavior so check empty() first.
Tested. Python 3.13.18 compared the list stack and the linked stack with a model on 3,000 random operation sequences and all agreed. g++ 13.3 compiled the C++ version with warnings on. Tests ran in a cloud sandbox.
What Is the Time and Space Complexity of a Stack?
Push, pop, peek and isEmpty touch only the top so all 4 stack operations take O(1) time. Space is O(n) for n stored items.
Test below pushed n integers and then popped all of them with a Python list. Table lists the lowest of 3 trials in CPython 3.13.18.
| Items pushed and popped | Total time | Time per stack operation |
|---|---|---|
| 10,000 | 0.0003 s | 16 ns |
| 100,000 | 0.0039 s | 20 ns |
| 1,000,000 | 0.0445 s | 22 ns |
Time per operation remains near a constant value while the stack grows 100 times. Total time grows with n and not with the size of the stack.
See time complexity for the notation.
Where Are Stacks Used in Real Software?
Every function call pushes a frame onto the call stack. Finished calls pop their frame.
Deep recursion piles up frames and Python raises RecursionError at 1,000 frames by default. See how recursion works for a traced example.
Editors can store undo history as a stack. Every action is pushed and undo pops the latest one. Bracket checking is another use and the code below was tested.
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for char in text:
if char in "([{":
stack.append(char)
elif char in pairs:
if not stack or stack.pop() != pairs[char]:
return False
return not stack
print(is_balanced("([]{})"), is_balanced("([)]"), is_balanced("(("))
Output is True False False. Every opening bracket is pushed and every closing bracket must match the popped one.
Matching strings end with an empty stack. 3,000 random bracket strings matched a reference check.
Practice the pattern in the stack practice set and open the valid parentheses visualiser to watch the stack grow and shrink.
Frequently Asked Questions
What Does LIFO Mean in a Stack?
Last in first out. Newest items are removed first. This rule defines how a stack behaves.
Do Stack Operations Take Constant Time?
Yes. Push, pop, peek and isEmpty take O(1) time because they touch only the top. Space is O(n) for n stored items.
How Do a Stack and a Queue Differ?
Stacks remove the newest item first. Queues remove the oldest item first like a line at a counter. See the queue lesson.
What Happens if You Pop an Empty Stack?
It is called stack underflow. Python code above returns None. C++ calls on an empty stack are undefined behavior so check empty first.
Can a Linked List Build a Stack?
Yes. Approach #2 above does it with linked nodes. Push and pop take O(1) time and no resizing is needed.
Why Is the Call Stack Called a Stack?
Function calls are pushed on top and removed from the top in last in first out order. That is the stack rule.
Can a Python List Work as a Stack?
Yes. Its append method pushes and its pop method removes the last item. Both took about 20 ns per operation in the test above.
What Should You Remember About the Stack Data Structure?
Add to the top and remove from the top. Every stack data structure follows that rule.
Key takeaways.
- Every stack operation takes O(1) time and space is O(n).
- Lists and linked nodes both build a stack.
- Call stacks and bracket checks rely on the same rule.
Check yourself. Push 5 then 2 then 8 and pop once. Which value comes off and what is on top? Answer is 8 comes off and 2 is on top.