Stacks and Queues in Detail
Stacks and Queues in Detail
Stacks and queues are both linear data structures that allow you to store and retrieve data in a
specific order. They both differ in how elements are added and removed.
1. Stack
A stack is a data structure that follows the Last In, First Out (LIFO) principle. This means that the
last element added to the stack is the first one to be removed.
3. Peek (Top): Get the element at the top without removing it.
Example of a Stack:
Consider a stack of books. If you add a book to the top of the stack, the book you added last will
be the first one you can remove.
class Stack:
def __init__(self):
self.stack = []
self.stack.append(item)
def pop(self):
if self.is_empty():
def peek(self):
if self.is_empty():
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
# Example Usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
In this example:
2. Queue
A queue is a data structure that follows the First In, First Out (FIFO) principle. This means that
the first element added to the queue is the first one to be removed.
3. Peek (Front): Get the element at the front without removing it.
Example of a Queue:
Consider a line of people waiting for a bus. The first person to get in line is the first person to get
on the bus.
class Queue:
def __init__(self):
self.queue = []
self.queue.append(item)
def dequeue(self):
if self.is_empty():
return self.queue.pop(0)
def peek(self):
if self.is_empty():
def is_empty(self):
return len(self.queue) == 0
def size(self):
return len(self.queue)
# Example Usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
In this example:
Order of
Last In, First Out (LIFO) First In, First Out (FIFO)
Elements
Insertion Elements are added at the top Elements are added at the rear
Real-world Applications:
• Stack:
o Function call stack: In programming, function calls are pushed onto a stack.
• Queue:
Visualization
• Stack:
• [2]
• [1]
• Queue: