Unit3 - Stack & Queues
Unit3 - Stack & Queues
Unit:3
Data Structure
ACSE0301 Ms. Pragya Singh
Assistant Professor
B Tech 3rd Sem
(CSE)
Qualification:
Topics Duration
(in Hours)
Stacks: Abstract Data Type 1
Array and Linked Implementation of Stack in Python 1
Application of stack: Prefix and Postfix Expressions 1
Evaluation of postfix expression 1
Iteration and Recursion- Principles of recursion 1
Binary search using recursion 1
Hanoi towers 1
Tradeoffs between iteration and recursion. 2
ACSE0301.1 3 3 3 2 - 1 - 1 2 2 2 2
ACSE0301.2 3 3 2 2 - 1 - 1 2 2 1 2
ACSE0301.3 3 3 2 2 - 1 - 1 2 2 2 2
ACSE0301.4 3 3 2 2 - 1 - 1 2 2 2 2
ACSE0301.5 3 3 3 3 2 2 2 2 3 3 3 3
Average 3 3 2.4 2.2 0.4 1.2 0.4 1.2 2.2 2.2 2 2.2
PSO 3: The ability to conduct investigation of complex problem with the help of
technical, managerial, leadership qualities, and modern engineering tools provided by
industry sponsored laboratories.
PSO 4: The ability to identify, analyze real world problem and design their solution
using artificial intelligence ,robotics, virtual. Augmented reality ,data analytics, block
chain technology and cloud computing.
ACSE0301.1 3 3 2 2
ACSE0301.2 3 3 2 3
ACSE0301.3 3 3 2 2
ACSE0301.4 3 3 3 3
ACSE0301.5 3 3 3 3
Stack - 2 - - -
Queue - 2 - - -
Stack Operations
Top: Open end of the stack is called Top, From this end item can
be inserted.
POP: To put-off, get or remove some item from top of the stack is
the pop operation, We can POP only only from top of the stack.
Stack Operations
Stack Example
• Using Array
Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
Step 2 - Declare all the functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the
stack.
Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with
top. Display stack[i] value and decrement i value by one (i--).
The major problem with the stack implemented using an array is, it works
only for a fixed number of data values.
Stack implemented using an array is not suitable, when we don't know the
size of data which we are going to use.
Stack implemented using linked list works for the variable size of data.
So, there is no need to fix the size at the beginning of the implementation.
Whenever we want to remove an element from the stack, simply remove the node which
is pointed by 'top' by moving 'top' to its previous node in the list. The next field of the
first element must be always NULL.
Step 1 - Include all the header files which are used in the program.
And declare all the user defined functions.
We can use the following steps to insert a new node into the stack...
Step 1 - Create a newNode with given value.
We can use the following steps to delete a node from the stack...
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to
'top’.
Step 4 - Display 'temp → data --->' and move it to the next node.
Repeat the same until temp reaches to the first node in the stack. (temp
→ next != NULL).
Reverse String...
Reverse String...
What is an Expression?
In any programming language, if we want to perform any calculation or to frame
a condition etc., we use a set of symbols to perform the task. These set of symbols
makes an expression.
An expression can be defined as follows...
Operands are the values on which the operators can perform the task. Here
operand can be a direct value or variable or address of memory location
Expression Types
Based on the operator position, expressions are divided into
THREE types.
1.Infix Expression
2.Postfix Expression
3.Prefix Expression
+AB
Postfix Expression: An expression in which
operator follows its two operands is called a postfix expression.
AB+
a. 2*3/(2-1)+5*(4-1)
b. (2*3)/(2-1)+5*(4-1)
c. ((2*3)/(2-1))+(5*(4-1))
d. ((2*3)/(2-1))+(5*(4-1))
e. ((2*3)/(2-1))+(5*(4-1))
f. (((2*3)/(2-1))+(5*(4-1)))
Ans. 23*21-/541-*+
H.W
1. A+B*C-D^E^F
Exercise:
1. Infix ( (A * B) + (C / D) ) to Prefix
2.Infix ((A * (B + C) ) / D) to Prefix
3.Infix (A * (B + (C / D) ) ) to Prefix
27/02/2024 47
Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack
Infix to Postfix using Stack (Convert in Reverse Polish Notation)
1. Examine the given Input Sequence.
2. If it is operand output it.
3. If it is ‘(‘ push it on the stack.
4. If it is an operator and
a) If the stack is empty push it on the stack.
b) If the top of the stack is ‘(‘ then push it on to the stack.
c) If it has higher priority then top of the stack, push it on to the
stack.
d) Otherwise pop operator from the stack and output it. And go to
step 4.
5. If it is ‘)’ then pop of the operators from the stack and output them
until ‘(‘ is encountered.
6. If there are more input sequence then go to step 1.
7. If there are no more input sequence, pop of remaining elements from
the stack and output them.
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 48
Introduction to Stack
This is how you convert manually for theory question in the exam
Input String - Infix – ((a/b)+c)-(d+(e*f))
1.String after reversal – ))f*e(+d(-)c+)b/a((
2.String after interchanging right and left parenthesis – ((f*e)+d)-
(c+(b/a))
3.Apply postfix
4.Reverse Postfix Expression (Given After the table below)
-+/abc+d*ef
Types of Recursions:
Recursion are mainly of two types depending on whether a function calls itself from
within itself or more than one function call one another mutually. The first one is
called direct recursion and another one is called indirect recursion.
fun()
Fun1( ) Fun2( )
{
{ {
-------------
------------
----------
Fun2( ) Fun1( )
fun()
}
} }
Recursion
• There is base condition, that stops further calling of the function
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
# user input
num = 5
def factorial(n):
res = 1
# Driver Code
num = 5;
print("Factorial of", num, "is", factorial(num))
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n_terms = 5
def facto(n):
if (n == 0):
return 1
return n * facto(n-1)
if (n == 0):
return a
return facto(n - 1, n * a)
• Cons
• Recursive functions are generally slower than non-recursive
functions.
• May require a lot of memory to hold intermediate results on the
system stack.
• It is difficult to think recursively so one must be very careful
when writing recursive functions.
else:
# Element is not present in the array
return -1
2. Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
77
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack
78
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack
# Driver code
n=4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
79
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack
27/02/2024 82
Ms. Pragya Singh ACSE-0301 and DS Unit -3
Recursion
• Difference Between Recursion and Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Speed Slow in execution. Fast in execution.
Size of Code Recursion reduces the size of Iteration makes the code
the code. longer.
Queue
Implementation of Queue
1. Using Array
2. Using Link List
Application of Queue
• Queue is used to implement many algorithms like Breadth First Search (BFS), etc.
• It can be also used by an operating system when it has to schedule jobs with equal
priority
• Customers calling a call center are kept in queues when they wait for someone to
pick up the calls
10
A[0] A[1] A[2] A[3] A[4]
F=R=0
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 86
Queue
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
Although, the technique of creating a queue is easy, but there are some
drawbacks of using this technique to implement a queue.
Types Of Queue
1. Circular Queue
2. Priority Queue
3. Double Ended Queue (Deque)
• Problem:
– Wastage of memory in standard queue during deletion operation
We can use the following steps to display the elements of a circular queue...
Priority Queue
DATA PRIORTY
NUMBER
A 5
B 1
D 3
E 2
F 8
G 6
Insertion Operation:
• While inserting elements in priority queue we will add it at the
appropriate position depending on its priority
Deletion Operation:
• While deletion, the element having highest priority is always deleted
first.
DATA PRIORTY
NUMBER
B 1
E 2
D 3
A 5
G 6
F 8
2. Dijkstra's shortest path algorithm implementation can be done using priority queues.
5. Priority queues are used in operating system for load balancing and interrupt handling.
7. In traffic light, depending upon the traffic, the colors will be given priority.
Types of Deque
Insert At Right
void insert_right()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow\n");
return;}
if (left == -1) /* if queue is initially empty */
{ left = 0;
right = 0;}
else
if(right == MAX-1) /*right is at last position of queue */
right = 0;
else
right = right+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[right] = added_item ;
}
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 112
Queue
Insert At Left
void insert_left()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow \n");
return; }
if (left == -1)/*If queue is initially empty*/
{
left = 0;
right = 0; }
else
if(left== 0)
left=MAX-1;
else
left=left-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[left] = added_item ;
}
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 113
Queue
Delete from Left
void delete_left()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[left]);
if(left == right) /*Queue has only one element */
{ left = -1;
right=-1;
}
else
if(left == MAX-1)
left = 0;
else
left = left+1;
}
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 114
Queue
Delete from right
void delete_right()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[right]);
if(left == right) /*queue has only one element*/
{ left = -1;
right=-1; }
else
if(right == 0)
right=MAX-1;
else
right=right-1;
}
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 115
Queue
Application of Deque –
Deque is a Double Ended Queue where operations(Add/Remove) can be made on both
ends of the queue.
1.A web browser's history. Recently visited URLs are added to the front of the deque,
and the URL at the back of the deque is removed after some specified number of
insertions at the front.
3.Have you see moneyControl App, it will show the stocks you last visited, it will
remove the stocks after some time and will add the latest ones.
https://www.youtube.com/watch?v=PGWZUgzDMYI&list=PLBF3763AF2E1
C572F&index=3
https://www.youtube.com/watch?v=zp6pBNbUB2U&list=PLdo5W4Nhv31bb
KJzrsKfMpo_grxuLl8LU&index=41
https://www.youtube.com/watch?v=UpvDOm3prfI
Q 2 Consider the following infix expression and convert into reverse polish
notation using stack. A + (B * C – (D / E ^ F) * H)
Q5. The initial configuration of a queue is p,q,r,s (‘p’ is in the front end ). To get the
configuration s,r,q,p, how many minimum dequeue and enqueue are required?
Q.6 What is Tower of Hanoi Problem? Explain the solution of Tower of Hanoi
Problem where discs are 4 and pegs is 3.
4. Pushing an element into stack already having five elements and stack
size of 5, then stack becomes
a) Overflow
b) Crash
c) Underflow
d) User flow
9. If the elements “A”, “B”, “C” and “D” are placed in a queue and are
deleted one at a time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
1. In a stack, if a user tries to remove an element from empty stack it is called _________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
2. Pushing an element into stack already having five elements and stack size of 5, then
stack becomes
a) Overflow
b) Crash
c) Underflow
d) User flow
7.If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a
time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
8. A data structure in which elements can be inserted or deleted at/from both the ends
but not in the middle is?
a) Queue
b) Circular queue
c) Dequeue
d) Priority queue