0% found this document useful (0 votes)
3 views

unit 4-stack and queue-1

The document provides an overview of stacks and queues as linear data structures, detailing their implementations, operations, and applications. It explains stack operations such as push, pop, and peek, as well as queue operations like enqueue and dequeue, and discusses their real-life applications. Additionally, it covers advantages and disadvantages of these data structures, along with methods for infix to postfix conversion and checking for balanced brackets.

Uploaded by

molej65141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

unit 4-stack and queue-1

The document provides an overview of stacks and queues as linear data structures, detailing their implementations, operations, and applications. It explains stack operations such as push, pop, and peek, as well as queue operations like enqueue and dequeue, and discusses their real-life applications. Additionally, it covers advantages and disadvantages of these data structures, along with methods for infix to postfix conversion and checking for balanced brackets.

Uploaded by

molej65141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Open Elective2:

Subject: Data structures using


Python
Unit 4:Stack and Queue
Content

► Stacks - Overview of Stack, Implementation of Stack, Applications of Stack,


► Queues- Overview of Queue, Implementation of Queue, Applications of Queues,
Priority Queues.

Dr. M. A. Rajnaikar, PCCOE,Pune 2


Stack-Introduction

► A stack is a linear data structure that stores items in a Last-In/First-Out


(LIFO) or First-In/Last-Out (FILO) manner.
► In stack, a new element is added at one end and an element is removed from
that end only.
► The insert and delete operations are often called push and pop.

Dr. M. A. Rajnaikar, PCCOE,Pune 3


LIFO Principle of Stack

► Here, you can:


• Put a new plate on top
• Remove the top plate
► And, if you want the plate at the bottom, you must first remove all the plates on
top. This is exactly how the stack data structure works.

Dr. M. A. Rajnaikar, PCCOE,Pune 4


some basic operations

► 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

Dr. M. A. Rajnaikar, PCCOE,Pune 5


Working of Stack Data Structure
The operations work as follows:
► A pointer called TOP is used to keep track of the
top element in the stack.
► When initializing the stack, we set its value to -1 so
that we can check if the stack is empty by
comparing TOP == -1.
► On pushing an element, we increase the value of
TOP and place the new element in the position
pointed to by TOP.
► On popping an element, we return the element
pointed to by TOP and reduce its value.
► Before pushing, we check if the stack is already full
► Before popping, we check if the stack is already
empty

Dr. M. A. Rajnaikar, PCCOE,Pune 6


The functions associated with stack
are
• empty() – Returns whether the stack is empty – Time Complexity: O(1)
• size() – Returns the size of the stack – Time Complexity: O(1)
• top() / peek() – Returns a reference to the topmost element of the stack – Time
Complexity: O(1)
• push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity:
O(1)
• pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

Dr. M. A. Rajnaikar, PCCOE,Pune 7


Implementation:

► 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

Dr. M. A. Rajnaikar, PCCOE,Pune 8


Implementation using list:
► Python’s built-in data structure list can be used as a stack. Instead of push(),
append() is used to add elements to the top of the stack while pop() removes the
element in LIFO order.
► Unfortunately, the list has a few shortcomings.
► The biggest issue is that it can run into speed issues as it grows. The items in the
list are stored next to each other in memory, if the stack grows bigger than the
block of memory that currently holds it, then Python needs to do some memory
allocations. This can lead to some append() calls taking much longer than other
ones.

Dr. M. A. Rajnaikar, PCCOE,Pune 9


Dr. M. A. Rajnaikar, PCCOE,Pune 10
Stack using Array

Step-by-step approach:

1. Initialize an array to represent the stack.


2. Use the end of the array to represent the top of the stack.
3. Implement push (add to end), pop (remove from the end), and
peek (check end) operations, ensuring to handle empty and full
stack conditions.
Initializing the Stack
To create a stack, we need an array to hold the elements and an index to keep track of the top
element.

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:

def push(self, item):

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.

Dr. M. A. Rajnaikar, PCCOE,Pune 15


Dr. M. A. Rajnaikar, PCCOE,Pune 16
Dr. M. A. Rajnaikar, PCCOE,Pune 17
Applications of Stack Data
Structure
► To reverse a word - Put all the letters in a stack and pop them out.
Because of the LIFO order of stack, you will get the letters in reverse
order.
► In compilers - Compilers use the stack to calculate the value of
expressions like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix
or postfix form.

► 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.

► Stacks can be used for Backtracking, i.e., to check parenthesis matching


in an expression

Dr. M. A. Rajnaikar, PCCOE,Pune 18


Application of Stack in real life:

• 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 ).

Dr. M. A. Rajnaikar, PCCOE,Pune 19


Advantages of Stack:

• Stack helps in managing data that follows the LIFO technique.


• Stacks are be used for systematic Memory Management.
• It is used in many virtual machines like JVM.
• When a function is called, the local variables and other function parameters are
stored in the stack and automatically destroyed once returned from the function.
Hence, efficient function management.
• Stacks are more secure and reliable as they do not get corrupted easily.
• Stack allows control over memory allocation and deallocation.
• Stack cleans up the objects automatically.

Dr. M. A. Rajnaikar, PCCOE,Pune 20


Disadvantages of Stack:

• Stack memory is of limited size.


• The total of size of the stack must be defined before.
• If too many objects are created then it can lead to stack overflow.
• Random accessing is not possible in stack.
• If the stack falls outside the memory it can lead to abnormal termination.

Dr. M. A. Rajnaikar, PCCOE,Pune 21


Infix to postfix conversion

Dr. M. A. Rajnaikar, PCCOE,Pune 22


Dr. M. A. Rajnaikar, PCCOE,Pune 23
Infix to Postfix Conversion
► The algorithm is:
1. Create an empty stack and an empty postfix output string/stream
2. Scan the infix input string/stream left to right
3. If the current input token is an operand, simply append it to the output string
4. If the current input token is an operator, pop off all operators that have equal or higher precedence and append
them to the output string; push the operator onto the stack. The order of popping is the order in the output.
5. If the current input token is '(', push it onto the stack
6. If the current input token is ')', pop off all operators and append them to the output string until a '(' is popped;
discard the '('.
7. If the end of the input string is found, pop all operators and append them to the output string.

► Apply the algorithm to the above expressions.

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.

2) Scan the given expression and do following for every scanned


element.
(a)If the element is a number, push it into the stack.
(b) If the element is an operator, pop operands for the operator from
stack. Evaluate the operator and push the result back to the stack.

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

► The idea is to put all the


opening brackets in the stack
and whenever you hit a closing
bracket. Search if the top of the
stack is the opening bracket of
the same nature. If this holds
then pop the stack and
continue the iteration , in the
end if the stack is empty, it
means all brackets are well-
formed and return Balanced ,
else return Not Balanced.
Dr. M. A. Rajnaikar, PCCOE,Pune 33
Algorithm:

• If the character is a opening parenthesis, push it onto the stack.


• If the character is a closing parenthesis:
• If the stack is nonempty, and the current character matches the character
on top of the stack, remove the character from the top of the stack.
• Otherwise, the string is not matched.
• Ignore all other characters

Dr. M. A. Rajnaikar, PCCOE,Pune 34


Dr. M. A. Rajnaikar, PCCOE,Pune 35
Queue Data structure

► 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.

Dr. M. A. Rajnaikar, PCCOE,Pune 36


Operations on Queue:

► Operations associated with queue are:

• 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)

Dr. M. A. Rajnaikar, PCCOE,Pune 37


Working of Queue

► Queue operations work as follows:


• two pointers FRONT and REAR
• FRONT track the first element of the queue
• REAR track the last element of the queue
• initially, set value of FRONT and REAR to -1

Dr. M. A. Rajnaikar, PCCOE,Pune 38


Enqueue and Dequeue Operation

► 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

Dr. M. A. Rajnaikar, PCCOE,Pune 40


Implementation :

► 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

Dr. M. A. Rajnaikar, PCCOE,Pune 41


Implementation using list

► List is a Python’s built-in data structure that can be used as a queue.


► Instead of enqueue() and dequeue(), append() and pop() function is used.
► However, lists are quite slow for this purpose because inserting or deleting an
element at the beginning requires shifting all of the other elements by one,
requiring O(n) time.

Dr. M. A. Rajnaikar, PCCOE,Pune 42


Dr. M. A. Rajnaikar, PCCOE,Pune 43
Implementation using 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:

• maxsize – Number of items allowed in the queue.


• empty() – Return True if the queue is empty, False otherwise.
• full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the
default), then full() never returns True.
• get() – Remove and return an item from the queue. If queue is empty, wait until an item is available.
• get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
• put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the
item.
• put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately available, raise
QueueFull.
• qsize() – Return the number of items in the queue.
Dr. M. A. Rajnaikar, PCCOE,Pune 44
Dr. M. A. Rajnaikar, PCCOE,Pune 45
Applications of Queue

• CPU scheduling, Disk Scheduling


• When data is transferred asynchronously between two processes. The queue is
used for synchronization. For example: IO Buffers, pipes, file IO, etc
• Handling of interrupts in real-time systems.
• Call Center phone systems use Queues to hold people calling them in order.

Dr. M. A. Rajnaikar, PCCOE,Pune 46


Priority Queue
► A priority queue is a special type of queue in which each element is associated with
a priority value. And, elements are served on the basis of their priority. That is,
higher priority elements are served first.
► However, if elements with the same priority occur, they are served according to their
order in the queue.
► Priority Queue is an extension of the queue with the following properties.
1. An element with high priority is dequeued before an element with low priority.
2. If two elements have the same priority, they are served according to their order in the
queue.
Various applications of the Priority queue in Computer Science are:
Job Scheduling algorithms, CPU and Disk Scheduling, managing resources that are
shared among different processes, etc.

Dr. M. A. Rajnaikar, PCCOE,Pune 47


Assigning Priority Value

► 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.

Dr. M. A. Rajnaikar, PCCOE,Pune 48


Key differences between Priority Queue and
Queue:

1. In Queue, the oldest element is dequeued first. While, in Priority Queue, an


element based on the highest priority is dequeued.
2. When elements are popped out of a priority queue the result obtained is either
sorted in Increasing order or in Decreasing Order. While, when elements are
popped from a simple queue, a FIFO order of data is obtained in the result.

Dr. M. A. Rajnaikar, PCCOE,Pune 49


Priority Queue Applications

► Some of the applications of a priority queue are:


• Dijkstra's algorithm
• for implementing stack
• for load balancing and interrupt handling in an operating system
• for data compression in Huffman code

Dr. M. A. Rajnaikar, PCCOE,Pune 50

You might also like