Introduction
When studying data structures, two of the most important linear structures after arrays and linked lists are Stacks and Queues.
They are widely used in programming, algorithm design, and even real-world systems like task scheduling, expression evaluation, and memory management.
What is a Stack?
A Stack is a linear data structure that follows the principle of LIFO (Last In, First Out). This means the last element added to the stack will be the first one removed — just like a stack of plates or books.
Real-Life Example
Imagine stacking books:
You put book A, then B, then C on top.
When you remove one, you take C first, because it’s on top.
Stack Representation
Top → [C]
[B]
[A]The last element you pushed (C) will be the first one to pop out.
Stack Operations
| Operation | Description | Example | Time Complexity |
|---|---|---|---|
| push(x) | Add an element x to the top | push(10) | O(1) |
| pop() | Remove the top element | pop() → 10 | O(1) |
| peek() / top() | View the top element without removing it | peek() → 10 | O(1) |
| isEmpty() | Check if stack is empty | True / False | O(1) |
Python Implementation of Stack
Python does not have a built-in Stack class, but you can easily implement one using lists or collections.deque.
Example 1: Stack using List
class Stack:
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def pop(self):
if not self.is_empty():
return self.items.pop()
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.items[-1]
return "Stack is empty"
def is_empty(self):
return len(self.items) == 0
def display(self):
print("Stack:", self.items)
# Example usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
s.display()
print("Popped:", s.pop())
print("Top Element:", s.peek())
Output:
Stack: [10, 20, 30]
Popped: 30Top Element: 20Real-Life Uses of Stack
Undo/Redo operations in text editors
Backtracking algorithms (like solving mazes, DFS in graphs)
Function call management (call stack in programming)
Expression evaluation (Postfix, Prefix conversion)
Web browser history (back button uses stack behavior)
What is a Queue?
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle.
This means the first element added to the queue will be the first one removed — like a line of people waiting for tickets.
Real-Life Example
Imagine a queue at a ticket counter:
The first person in line is served first.
New people join at the end.
Queue Representation
Front → [A][B][C] ← Rear
If A entered first, A will also leave first.

Join the conversation! Your thoughts help the community grow.