unit 4-stack and queue-1
unit 4-stack and queue-1
► There are some basic operations that allow us to perform different actions on a
stack.
• Push: Add an element to the top of a stack
• Pop: Remove an element from the top of a stack
• IsEmpty: Check if the stack is empty
• IsFull: Check if the stack is full
• Peek: Get the value of the top element without removing it
► There are various ways from which a stack can be implemented in Python.
► Stack in Python can be implemented using the following ways:
• list
• Collections.deque
• queue.LifoQueue
Step-by-step approach:
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = [None] * capacity
self.top = -1
Push Operation
Adding an element to the stack is known as the "push" operation. Here's how it can be
implemented:
if self.top == self.capacity - 1:
print("Stack Overflow")
return
self.top += 1
self.stack[self.top] = item
Pop Operation
The "pop" operation removes and returns the top element from
the stack:
def pop(self):
if self.top == -1:
print("Stack Underflow")
return None
item = self.stack[self.top]
self.top -= 1
return item
class Stack: def size(self):
def __init__(self): return len(self.stack)
self.stack = []
def is_empty(self):
return len(self.stack) == 0 # Example usage:
stack = Stack()
def push(self, item):
self.stack.append(item) stack.push(1)
stack.push(2)
def pop(self): stack.push(3)
if not self.is_empty():
return self.stack.pop() print("Stack:", stack.stack) # Output: Stack: [1, 2, 3]
else:
print("Stack is empty. Cannot pop.") print("Peek:", stack.peek()) # Output: Peek: 3
return None
print("Pop:", stack.pop()) # Output: Pop: 3
def peek(self): print("Stack:", stack.stack) # Output: Stack: [1, 2]
if not self.is_empty():
return self.stack[-1] print("Is Empty?", stack.is_empty()) # Output: Is
else: Empty? False
print("Stack is empty. Cannot peek.")
return None print("Stack Size:", stack.size()) # Output:
Stack Size: 2
Implementation using a singly linked list:
► The linked list has two methods addHead(item) and removeHead() that run in
constant time. These two methods are suitable to implement a stack.
• getSize()– Get the number of items in the stack.
• isEmpty() – Return True if the stack is empty, False otherwise.
• peek() – Return the top item in the stack. If the stack is empty, raise an
exception.
• push(value) – Push a value into the head of the stack.
• pop() – Remove and return a value in the head of the stack. If the stack is
empty, raise an exception.
► In browsers - The back button in a browser saves all the URLs you have
visited previously in a stack. Each time you visit a new page, it is added
on top of the stack. When you press the back button, the current URL is
removed from the stack, and the previous URL is accessed.
• CD/DVD stand.
• Stack of books in a book shop.
• Undo and Redo mechanism in text editors.
• The history of a web browser is stored in the form of a stack.
• Call logs, E-mails, and Google photos in any gallery are also stored in form of a
stack.
• YouTube downloads and Notifications are also shown in LIFO format(the latest
appears first ).
24
Dr. M. A. Rajnaikar, PCCOE,Pune 25
Dr. M. A. Rajnaikar, PCCOE,Pune 26
Example= A + B * C / D - E
27
Example
28
Dr. M. A. Rajnaikar, PCCOE,Pune 29
Evaluation of postfix
expression
► Following is the method for evaluation postfix expressions:
1) Create a stack to store operands.
3) When the expression is ended, the number in the stack is the final
answer
30
31
Dr. M. A. Rajnaikar, PCCOE,Pune 32
Check for Balanced
Brackets/parentheses in
an expression using Stack
► Like stack, queue is a linear data structure that stores items in First In First Out
(FIFO) manner.
► With a queue the least recently added item is removed first.
► A good example of queue is any queue of consumers for a resource where the
consumer that came first is served first.
• Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition – Time Complexity : O(1)
• Dequeue: Removes an item from the queue. The items are popped in the same
order in which they are pushed. If the queue is empty, then it is said to be an
Underflow condition – Time Complexity : O(1)
• Front: Get the front item from queue – Time Complexity : O(1)
• Rear: Get the last item from queue – Time Complexity : O(1)
► Enqueue Operation
• check if the queue is full
• for the first element, set the value of FRONT to 0
• increase the REAR index by 1
• add the new element in the position pointed to by REAR
► Dequeue Operation
• check if the queue is empty
• return the value pointed by FRONT
• increase the FRONT index by 1
• for the last element, reset the values of FRONT and REAR to -1
Dr. M. A. Rajnaikar, PCCOE,Pune 39
Example
► There are various ways to implement a queue in Python. This article covers the
implementation of queue using data structures and modules from Python
library.
Queue in Python can be implemented by the following ways:
• list
• array
• linked list
• collections.deque
• queue.Queue
► Queue is built-in module of Python which is used to implement a queue. queue.Queue(maxsize) initializes a
variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue. This Queue follows
FIFO rule.
There are various functions available in this module:
► Generally, the value of the element itself is considered for assigning the priority.
For example,
► The element with the highest value is considered the highest priority element.
However, in other cases, we can assume the element with the lowest value as
the highest priority element.
► We can also set priorities according to our needs.