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

Unit3 - Stack & Queues

This document discusses a unit on stacks, queues, and recursion taught by Ms. Pragya Singh. It provides an overview of the topics covered, including stack operations, array and linked implementations of stacks, applications of stacks, queues, and recursion. It also outlines the learning objectives, evaluation scheme, syllabus, and how the unit maps to course and program outcomes.

Uploaded by

jatinsingh150815
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Unit3 - Stack & Queues

This document discusses a unit on stacks, queues, and recursion taught by Ms. Pragya Singh. It provides an overview of the topics covered, including stack operations, array and linked implementations of stacks, applications of stacks, queues, and recursion. It also outlines the learning objectives, evaluation scheme, syllabus, and how the unit maps to course and program outcomes.

Uploaded by

jatinsingh150815
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 141

Noida Institute of Engineering and

Technology, Greater Noida


Stacks, Queues

Unit:3

Data Structure
ACSE0301 Ms. Pragya Singh
Assistant Professor
B Tech 3rd Sem
(CSE)

Ms. Pragya Singh ACSE-0301 and DS Unit -3


1
27/02/2024
Brief Introduction of Faculty member

Name : Ms. Pragya Singh


Designation: Assistant Professor (2K23F065)
Department: CSE

Qualification:

 MCA from UPTU Lucknow, 2010


 M.Tech(CSE) from MDU Rohtak, 2016

Teaching Experience (Year): 9 years

Ms. Pragya Singh ACSE-0301 and DS Unit -3


27/02/2024 2
Evaluation Scheme

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 3


Syllabus
UNIT-3
Stacks: Primitive Stack operations: Push & Pop, Array and Linked
Implementation of Stack, Application of stack: Infix, Prefix, Postfix
Expressions and their mutual conversion, Evaluation of postfix
expression.

Recursion: Principles of recursion, Tail recursion, Removal of


recursion, Problem solving using iteration and recursion with
examples such as binary search, Fibonacci series, and Tower of
Hanoi, Trade-offs between iteration and recursion.

Queues: Array and linked implementation of queues, Operations on


Queue: Create, Insert, Delete, Full and Empty, Circular queues,
Dequeue and Priority Queue.
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 4
Contents

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 5


Contents

Topics Duration (in


Hours)
Queues: Operations on Queue 1
Circular queues 1
Array and linked implementation of queues in Python 1
Dequeue 1
Priority Queue 1

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 6


Objective of Unit

Objective of the course is to make students able to:

1. Learn the basic types for data structure, implementation and


application.
2. Know the strength and weakness of different data structures.

3. Use the appropriate data structure in context of solution of given


problem.

4. Develop programming skills which require to solve given problem.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 7


Course Outcome
Bloom’s
CO Description Knowledge
CO
Level (KL)

CO 1 Describe the need of data structure and algorithms in problem K2, K4


solving and analyze Time space trade-off.

Describe how arrays are represented in memory and how


CO 2 to use them for implementation of matrix operations, K2, K6
searching and sorting along with their computational
efficiency.

CO 3 Design, implement and evaluate the real-world applications K5, K6


using stacks, queues and non-linear data structures.

Compare and contrast the advantages and disadvantages of


CO 4 linked lists over arrays and implement operations on different K4, K6
types of linked list.
Identify and develop the alternative implementations of data
CO 5 structures with respect to its performance to solve a real- K1, K3, K5, K6
world problem.
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 8
Program Outcomes (POs)
1. Engineering knowledge
2. Problem analysis
3. Design/development of solutions
4. Conduct investigations of complex problems
5. Modern tool usage
6. The engineer and society
7. Environment and sustainability
8. Ethics
9. Individual and team work
10. Communication
11. Project management and finance
12. Life-long learning

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 9


CO-PO Mapping

CO-PO correlation matrix of Data Structure (KCS 301)


PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 10


Program Specific Outcomes (PSOs)
On successful completion of graduation degree the Engineering graduates will be able
to:
PSO1: The ability to design and develop the hardware sensor device and related
interfacing software system for solving complex engineering problem.

PSO2: The ability to understanding of Inter disciplinary computing techniques and to


apply them in the design of advanced computing .

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 11


CO-PSO Mapping

Mapping of Program Specific Outcomes and Course Outcomes

PSO1 PSO2 PSO3 PSO4

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

Average 3 3 2.4 2.6

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 12


Prerequisite and Recap

1. Stack is a container of objects that are inserted and removed according


to the last-in first-out (LIFO) principle.

2. Queue is a container of objects (a linear collection) that are inserted


and removed according to the first-in first-out (FIFO) principle.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 13


Stack and Queue(CO2)

Topic mapping with Course Outcome

Topic CO1 CO2 CO3 CO4 CO5

Stack - 2 - - -

Queue - 2 - - -

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 14


Introduction to Stack
Stack

A stack is a data structure in which


items can be inserted only from one
end and get items back from the
same end.

There , the last item inserted into


stack, is the the first item to be taken
out from the stack. In short its also
called Last in First out [LIFO].

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 15


Introduction to Stack

Example of Stack (LIFO)

● A Stack of book on table.

● Token stack in Bank.

● Stack of trays and plates.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 16


Introduction to Stack

Stack Operations

Top: Open end of the stack is called Top, From this end item can
be inserted.

Push: To insert an item from Top of stack is called push operation.


The push operation change the position of Top in stack.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 17


Introduction to Stack

Stack Operations

IsEmpty: Stack considered empty when there is no item on Top.


IsEmpty operation return true when no item in stack else false.

IsFull: Stack considered full if no other element can be inserted on


top of the stack. This condition normally occur when stack
implement ed through array.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 18


Introduction to Stack
Stack Abstract Data Type
ADT Stack {
Data/Attributes/Values:
int size; Top
Type items;
Functions/
Operations:
CreateStack (int size); --create stack of size Void
Push(int n); - - if stack is not full
Type Pop(); - - if stack is not empty return top item Int
isEmpty(); - - return true if empty otherwise false Int
isFull(); - - return true if full
27/02/2024 otherwise
Ms. Pragya false and
Singh ACSE-0301 } DS Unit -3 19
Introduction to Stack

Stack Example

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 20


Introduction to Stack
Implementation of Stack

• Using Array

• Using Link List

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 21


Introduction to Stack

Stack Implementation using Array ...

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 22


Introduction to Stack

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 23


Introduction to Stack

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 24


Introduction to Stack
Stack Implementation using Array
A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below steps to


create an empty stack.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 25


Introduction to Stack
push(value) - Inserting value into the stack using array
In a stack, push() is a function used to insert an element into the stack. In
a stack, the new element is always inserted at top position. Push function
takes one integer value as parameter and inserts that value into the stack.
We can use the following steps to push an element on to the stack...

 Step 1 - Check whether stack is FULL. (top == SIZE-1)

 Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is


not possible!!!" and terminate the function.

 Step 3 - If it is NOT FULL, then increment top value by one (top++)


and set stack[top] to value (stack[top] = value).

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 26


Introduction to Stack

pop() - Delete a value from the Stack using array


In a stack, pop() is a function used to delete an element from the stack. In
a stack, the element is always deleted from top position. Pop function
does not take any value as parameter. We can use the following steps to
pop an element from the stack...

 Step 1 - Check whether stack is EMPTY. (top == -1)

 Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion


is not possible!!!" and terminate the function.

 Step 3 - If it is NOT EMPTY, then delete stack[top] and


decrement top value by one (top--).

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 27


Introduction to Stack

display() - Displays the elements of a Stack using array


We can use the following steps to display the elements of a stack...

 Step 1 - Check whether stack is EMPTY. (top == -1)

 Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and


terminate the function.

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

 Step 3 - Repeat above step until i value becomes '0'.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 28


Introduction to Stack
Stack Implementation using Link List

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 29


Introduction to Stack
Stack Implementation using Link List
In linked list implementation of a stack, every new element is inserted as 'top' element.
That means every newly inserted element is pointed by 'top’.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 30


Introduction to Stack
Stack Implementation using Link List

To implement a stack using a linked list, we need to set the following


things before implementing actual operations.

 Step 1 - Include all the header files which are used in the program.
And declare all the user defined functions.

 Step 2 - Define a 'Node' structure with two


members data and next.

 Step 3 - Define a Node pointer 'top' and set it to NULL.

 Step 4 - Implement the main method by displaying Menu with list


of operations and make suitable function calls in the main method.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 31


Introduction to Stack

push(value) - Inserting an element into the Stack


using Link List

We can use the following steps to insert a new node into the stack...
 Step 1 - Create a newNode with given value.

 Step 2 - Check whether stack is Empty (top == NULL)

 Step 3 - If it is Empty, then set newNode → next = NULL


 .
 Step 4 - If it is Not Empty, then set newNode → next = top.

 Step 5 - Finally, set top = newNode.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 32


Introduction to Stack
pop() - Deleting an Element from a Stack using Link List

We can use the following steps to delete a node from the stack...

 Step 1 - Check whether stack is Empty (top == NULL).

 Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not


possible!!!" and terminate the function

 Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to
'top’.

 Step 4 - Then set 'top = top → next’.

 Step 5 - Finally, delete 'temp'. (free(temp)).

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 33


Introduction to Stack

display() - Displaying stack of elements using Link List


We can use the following steps to display the elements (nodes) of a stack...
 Step 1 - Check whether stack is Empty (top == NULL).

 Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate


the function.

 Step 3 - If it is Not Empty, then define a Node pointer 'temp' and


initialize with 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).

 Step 5 - Finally! Display 'temp → data ---> NULL'.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 34


Introduction to Stack
Stack Application

Reversing a string: To reverse a string we can use following algorithm.


1. Given the sting and a stack
2. While there is not end of string, do the following.
3. Read a character form the string
4. Push it on the stack
5. End while
6. Re-initialize string position
7. While stack is not Empty, do the following.
8. Pop a character from the stack
9.Insert the character popped into next position in string.
10.End While
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 35
Introduction to Stack

Reverse String...

String is a b c d e f PUSH to SACK


27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 36
Introduction to Stack

Reverse String...

Reversed String: f e d c b a POP from SACK

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 37


Introduction to Stack

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

An expression is a collection of operators and operands that represents a


specific value.

In above definition, operator is a symbol which performs a particular task like


arithmetic operation or logical operation or conditional operation etc.,

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 38


Introduction to Stack

Expression Types
Based on the operator position, expressions are divided into
THREE types.

They are as follows...

1.Infix Expression
2.Postfix Expression
3.Prefix Expression

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 39


Introduction to Stack

Infix, Postfix and Prefix Expression


Infix Expression: An expression in which the
operator is in between its two operands.
A+B
Prefix Expression: An expression in which operator precedes its
two operands is called an prefix expression.

+AB
Postfix Expression: An expression in which
operator follows its two operands is called a postfix expression.
AB+

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 40


Introduction to Stack

Infix to Postfix Conversion

Infix expression can be directly evaluated but the standard practice


in CS is that the infix expression converted to postfix form and then
the expression is evaluated.

During both processes stack is proved to be a useful data structure.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 41


Introduction to Stack
C language operators Precedence and Associativity

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 42


Introduction to Stack

Infix to Postfix By-Hand Algorithm

1. Given a expression in the infix form.


2. Find the highest precedence operator
3. If there are more then one operators with the same precedence
check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to postfix
(A + B)  A B+
5. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 43


Introduction to Stack

Q1. Convert the given infix expression 2*3/(2-1)+5*(4-1) to postfix


expression
Sol.

1. Enclosed in brackets, based on precedence and associativity

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 44


Introduction to Stack
2. Convert each bracket in postfix expression one by one
a. (((2*3)/(2-1))+(5*(4-1)))
b. (((23*)/(2-1))+(5*(4-1)))
c. (((23*)/(21-))+(5*(4-1)))
d. (((23*)/(21-))+(5*(41-)))
e. (((23*)(21-)/)+(5*(41-)))
f. (((23*)(21-)/)+(5(41-)*))
f. (((23*)(21-)/)(5(41-)*)+)

Ans. 23*21-/541-*+

H.W
1. A+B*C-D^E^F

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 45


Introduction to Stack

Infix to Prefix By-Hand Algorithm

1. Given a expression in the infix form.


2. Find the highest precedence operator
3. If there are more then one operators with the same precedence
check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to prefix
5. A+B --> +A B
6. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 46


Introduction to Stack

Infix to Prefix Step by Step Conversion

Q1. A*B+C/D (Infix) Q2. A*(B+C/D)


((A*B)+(C/D)) (A*(B+(C/D)) )
*AB+C/D A*(B+/CD)
*AB+/CD A*(+B/CD)

+*AB/CD (Prefix) *A+B/CD

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

Infix to Postfix using stack



Example A*B+C become AB*C+

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 49


Introduction to Stack

Infix to Postfix using stack ...


Example A * (B + C * D) + E becomes A B C D * + * E
+

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 50


Introduction to Stack
Infix to Prefix using Stack (Convert in Polish Notation)
1.First, reverse the given infix expression.
2.Scan the characters one by one.
3.If the character is an operand, print it .
4.If the character is a closing parenthesis, then push it to the stack.
5.If the character is an opening parenthesis, pop the elements in the
stack until we find the corresponding closing parenthesis.
6.If the character scanned is an operator
•If the operator has precedence greater than or equal to the top of the
stack, push the operator to the stack.
•If the operator has precedence lesser than the top of the stack, pop the
operator and output it to the prefix notation output and then check the
above condition again with the new top of the stack.
7. After all the characters are scanned, reverse the prefix notation
output

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 51


Introduction to Stack

Infix to Prefix using Stack..


Step 1: Reverse the infix expression i.e A+B*C will become C*B+A.
Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.

Step 2: Obtain the postfix expression of the modified expression i.e


CB*A+.

Step 3: Reverse the postfix expression. Hence in our example prefix is


+A*BC.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 52


Introduction to Stack
Algorithm for Prefix
•Step 1: Reverse the infix string. Note that while reversing the string
you must interchange left and right parentheses.
•Step 2: Obtain the postfix expression of the infix expression Step 1.
•Step 3: Reverse the postfix expression to get the prefix expression

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)

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 53


Introduction to Stack
Infix – ((a/b)+c)-(d+(e*f))  ))f*e(+d(-)c+)b/a((  ((f*e)+d)-(c+(b/a))

Sr. no. Expression Stack Prefix


0 ( (
1 ( ((
2 f (( f
3 * ((* f
4 e ((* fe
5 ) ( fe*
6 + (+ fe*
7 d (+ fe*d
8 ) fe*d+
9 – - fe*d+
10 ( -( fe*d+
11 c -( fe*d+c
12 + -(+ fe*d+c
13 ( -(+( fe*d+c
14 b -(+( fe*d+cb
15 / -(+(/ fe*d+cb
16 a -(+(/ fe*d+cba
17 ) -(+ fe*d+cba/
18 ) - fe*d+cba/+
19 fe*d+cba/+-

-+/abc+d*ef

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 54


Introduction to Stack
Infix – A*(B+D)/E-F*(G+H/K) --- > )K/H+G(*F-E/)D+B(*A -- > (K/H+G)*F-E/(D+B)*A

Sr. no. Expression Stack Prefix


1 ( (
2 K ( K
3 / (/ K
4 H (/ KH
5 + (+ KH/
6 G (+ KH/G
7 ) KH/G+
8 * * KH/G+
9 F * KH/G+F
10 - - KH/G+F*
11 E - KH/G+F*E
12 / -/ KH/G+F*E
13 ( -/( KH/G+F*E
14 D -/( KH/G+F*ED
15 + -/(+ KH/G+F*ED
16 B -/(+ KH/G+F*EDB
17 ) -/ KH/G+F*EDB+
18 * -/* KH/G+F*EDB+
19 A -/* KH/G+F*EDB+A
20 - KH/G+F*EDB+A*/-

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 55


Introduction to Stack

Evaluating Arithmetic Postfix Expression

1) Create a stack to store operands (or values).


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 a operator, pop two 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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 56


Introduction to Stack

Evaluating Arithmetic Postfix Expression


PostFix Expression 2 3 4 + * 5 *
Move Token Stack
1 2 2
2 3 23
3 4 234
4 + 27
(3+4=7)
5 * 14 (2*7=14)
6 5 14 5
7 * 70
(14*5=70)
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 57
Recursion
• Recursion is a process by which a function calls itself repeatedly,
until some specified condition has been satisfied

• To solve a problem recursively, two conditions must be satisfied.


• First, the problem must be written in a recursive form
• Second the problem statement must include a stopping
condition

def func(): <--


|
| (recursive call)
|
func() ----

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 58


Types of Recursion

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()
}
} }

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 59


Types of Recursion (contd..)

Other types of Recursion

Head Recursion() Tail Recursion() Head &Tail Recursion()

Fun() Fun() Fun()


{ { {
Fun(); ……. Fun()
……. …… ...….
…… ……. ……
……. Fun(); …….
} Fun();
}
}

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 60


Recursion

Recursion
• There is base condition, that stops further calling of the function

• Function call itself directly or indirectly, it should reach towards


base condition.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 61


Factorial of number using Recursion.
# Program to print factorial of a number recursively.

def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)

# user input
num = 5

# check if the input is valid or not


if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", factorial(num))

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 62


Factorial of number using Recursion.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 63


Factorial of number using Iteration
# Python program to find factorial of given number iteratively

def factorial(n):

res = 1

for i in range(2, n+1):


res *= i
return res

# Driver Code
num = 5;
print("Factorial of", num, "is", factorial(num))

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 64


Fibonacci series using Recursion

Program for Fibonacci numbers

• The Fibonacci numbers are the numbers in the following integer


sequence.

• 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

• In mathematical terms, the sequence Fn of Fibonacci numbers is


defined by the recurrence relation
Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 65


Fibonacci series using Recursion
# Program to print the fibonacci series upto n_terms

def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))

n_terms = 5

# check if the number of terms is valid


if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(fibonacci(i))
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 66
Fibonacci series using Recursion

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 67


Tail Recursion

# Program to calculate factorial of a number using a Non-Tail-


Recursive function.

def facto(n):

if (n == 0):
return 1

return n * facto(n-1)

# print the result


print(facto(6))

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 68


Tail Recursion (contd..)

# Program to calculate factorial of a number using a Tail-Recursive


function.

def facto(n, a = 1):

if (n == 0):
return a

return facto(n - 1, n * a)

# print the result


print(facto(6))

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 69


Recursion

Recursion Pros and Cons


• Pros
• The code may be much easier to write.
• To solve some problems which are naturally recursive such as
tower of Hanoi.

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 70


Binary Search

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 71


Binary Search

Python Program for Binary Search (Recursive and


Iterative)
This search algorithm takes advantage of a collection of
elements that is already sorted by ignoring half of the elements
after just one comparison.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid
index.
3. Else if x is greater than the mid element, then x can only lie
in the right (greater) half subarray after the mid element.
Then we apply the algorithm again for the right half.
4. Else if x is smaller, the target x must lie in the left (lower)
half. So we apply the algorithm for the left half.
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 72
Binary Search using Recursion
# program for recursive binary search. # Test array
# Returns index of x in arr if present, else -1 arr = [ 2, 3, 4, 10, 40 ]
def binary_search(arr, low, high, x): x = 10
# Check base case
if high >= low: # Function call
mid = (high + low) // 2 result = binary_search(arr, 0, len(arr)-1, x)
# If element is present at the middle itself
if arr[mid] == x: if result != -1:
return mid print("Element is present at index", str(result))
# If element is smaller than mid, then it can only else:
# be present in left subarray print("Element is not present in array")
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right


subarray
else:
return binary_search(arr, mid + 1, high, x)

else:
# Element is not present in the array
return -1

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 73


Binary Search using Iteration
# Iterative Binary Search Function # Test array
# It returns index of x in given array arr if present, else returns -1 arr = [ 2, 3, 4, 10, 40 ]
def binary_search(arr, x): x = 10
low = 0
high = len(arr) - 1 # Function call
mid = 0 result = binary_search(arr, x)
while low <= high:
mid = (high + low) // 2 if result != -1:
print("Element is present at index", str(result))
# If x is greater, ignore left half else:
if arr[mid] < x: print("Element is not present in array")
low = mid + 1

# If x is smaller, ignore right half


elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid
# If we reach here, then the element was not present
return -1
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 74
Introduction to Stack
Tower of Hanoi Problem

Tower of Hanoi is a mathematical puzzle where we have three rods and n


disks.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 75


Introduction to Stack
Tower of Hanoi Problem
The objective of the puzzle is to move the entire stack to another rod, obeying
the following simple rules:

1. Only one disk can be moved at a time.

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.

3. No larger disk may be placed on top of a smaller disk.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 76


Introduction to Stack

Tower of Hanoi Problem Illustration

77
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack

Tower of Hanoi Algorithm Concept

78
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3
Introduction to Stack

A recursive algorithm for Tower of Hanoi can be driven as follows


# Recursive Python function to solve the tower of hanoi

def TowerOfHanoi(n , source, auxiliary, destination):


if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, destination, auxiliary)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, source , destination)

# 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 Ms. Pragya Singh ACSE-0301 and DS Unit -3 80


Recursion
• Difference Between Recursion and Iteration
BASIS FOR COMPARISON RECURSION ITERATION
Basic The statement in a body of Allows the set of instructions
function calls the function to be repeatedly executed.
itself.
Format In recursive function, only Iteration includes
termination condition (base initialization, condition,
case) is specified. execution of statement within
loop and update (increments
and decrements) the control
variable.
Termination A conditional statement is The iteration statement is
included in the body of the repeatedly executed until a
function to force the function certain condition is reached.
to return without recursion call
being executed.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 81


Recursion
• Difference Between Recursion and Iteration
BASIS FOR COMPARISON RECURSION ITERATION
Condition If the function does not If the control condition in the
converge to some condition iteration statement never
called (base case), it leads to become false, it leads to
infinite recursion. infinite iteration.
Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles
system. repeatedly.
Applied Recursion is always applied to Iteration is applied to iteration
functions. statements or "loops".
Stack The stack is used to store the Does not uses stack.
set of new local variables and
parameters each time the
function is called.
Overhead Recursion possesses the No overhead of repeated
overhead of repeated function function call.
calls.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 83


Queue

Queue

• Queue is Linear Data Structure


• It follows First In First Out(FIFO) principal
• It has two pointers front and rear e.g.:
Front Rear

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 84


Queue

Implementation of Queue

1. Using Array
2. Using Link List

Application of Queue

Queues are used in a lot of applications, few of them are:

• 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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 85


Queue
Insertion in Queue using Array

A[0] A[1] A[2] A[3] A[4]


F=R=(-1)

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 87


Queue
Operations on Queue
Insertion:
Algorithm:

Step 1: If REAR = MAX – 1 then


Write “Queue is Overflow”
Goto step 4
[End of IF]
Step 2: IF FRONT=-1 and REAR=-1
SET FRONT=REAR=0
ELSE
SET REAR=REAR+1
[END OF IF]
Step 3: SET QUEUE [REAR] =
NUM
Step 4: EXIT
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 88
Queue

Example of Deletion in 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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 89


Queue

Example of Deletion in 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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 90


Queue
Operations on Queue
Deletion:
Algorithm:

Step 1: IF FRONT = -1 OR FRONT>REAR


Write “Queue is Underflow”
ELSE
SET VAL=QUEUE [FRONT]
FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 91


Queue
Drawback of array implementation

Although, the technique of creating a queue is easy, but there are some
drawbacks of using this technique to implement a queue.

Static Array Size

• Memory wastage : The space of the array, which is used to store


queue elements, can never be reused to store the elements of that
queue because the elements can only be inserted at front end and
the value of front might be so high so that, all the space before that,
can never be filled.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 92


Queue

Types Of Queue

1. Circular Queue
2. Priority Queue
3. Double Ended Queue (Deque)

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 93


Queue

Why Circular Queue is needed?

• Problem:
– Wastage of memory in standard queue during deletion operation

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 94


Queue

What is Circular Queue?

• The Arrangement of the elements Q[0], Q[1], ..,Q[n] in a circular


fashion with Q[1] following Q[n] is called Circular Queue.

• The last node is connected to first node


to make a circle.

• Initially, Both Front and Rear pointers points


to the beginning of the array.

• It is also known as “Ring Buffer”.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 95


Queue

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 96


Queue

Insertion in circular queue


Step 1 - Check whether Circular queue is FULL. Front ==
(Rear+1)%Max

Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion


is not possible!!!" and terminate the function.

Step 3 - If it is NOT FULL, then check Front == -1,


then Front = Rear = 0.

Step 4 - Rear = (Rear+1)%max, set Cqueue[Rear] = value.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 97


Queue

Deletion in circular queue


Step 1 - Check whether queue is EMPTY. (front == -1)

Step 2 - If it is EMPTY, then display “Circular Queue is EMPTY!!!


Deletion is not possible!!!" and terminate the function.

Step 3 - Val = Cqueue[front];


Step 4 – if(front==rear)
front = rear = -1;
Step 5 – front = (front+1)%Max;
Step 6 – return Val

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 98


Queue

display() - Displays the elements of a Circular Queue

We can use the following steps to display the elements of a circular queue...

Step 1 - Check whether queue is EMPTY. (front == -1)


Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
Step 4 – for(i = front; i!=rear; i = (i+1)%Max)
Print Cqueue[i];
end
print(queue[rear]);
Step 5 - Exit

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 99


Queue

Application of Circular Queue


Traffic light functioning is the best example for circular queues. The
colors in the traffic light follow a circular pattern.

In page replacement algorithms, a circular list of pages is maintained


and when a page needs to be replaced, the page in the front of the
queue will be chosen.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 100


Queue
Priority Queue

• In priority queue, each element is assigned a priority.


• Priority of an element determines the order in which the elements
will be processed.
• Rules:
1. An element with higher priority will processed before an
element with a lower priority.
2. Two elements with the same priority are processed on a
First Come First Serve basis.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 101


Queue

Priority Queue

DATA PRIORTY
NUMBER
A 5
B 1
D 3
E 2
F 8
G 6

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 102


Queue

Types of Priority Queue

1. Ascending Priority Queue


In this type of priority queue, elements can be inserted into any
order but only the smallest priority element can be removed.

2. Descending Priority Queue


In this type of priority queue, elements can be inserted into any
order but only the largest priority element can be removed.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 103


Queue

Array Representation of Priority Queue

Insertion Operation:
• While inserting elements in priority queue we will add it at the
appropriate position depending on its priority

• It is inserted in such a way that the elements are always ordered


either in Ascending or descending sequence

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 104


Queue

Array Insertion of Priority Queue

DATA PRIORTY DATA PRIORTY


NUMBER NUMBER
A 5 B 1
B 1 E 2
D 3 D 3
E 2 A 5
F 8 G 6
G 6 F 8

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 105


Queue

Array Representation of Priority Queue

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 106


Queue

Application of Priority Queue

1. Prim's algorithm implementation can be done using priority queues.

2. Dijkstra's shortest path algorithm implementation can be done using priority queues.

3. A* Search algorithm implementation can be done using priority queues.

4. Priority queues are used to sort heaps.

5. Priority queues are used in operating system for load balancing and interrupt handling.

6. Priority queues are used in huffman codes for data compression.

7. In traffic light, depending upon the traffic, the colors will be given priority.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 107


Queue

Deque / Double Ended Queue

• A list in which elements can be inserted or deleted either end

• It is also known as “Head-Tail Linked List”

• It has two pointers LEFT and RIGHT, which point to either


end of the deque.

• Dequeue can be implemented using Circular Array or a Circular


doubly linked list where Dequeue[n-1] is followed by
Dequeue[0]

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 108


Queue

Types of Deque

• Input Restricted Deque:-


In this dequeue, insertion can be done only at one of the end, while
deletion can be done from both ends.

• Output Restricted Deque:-


In this dequeue, deletion can be done only at one of the ends,
while insertions can be done on both ends.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 109


Queue

Input Restricted Deque

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 110


Queue

Output Restricted Deque

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 111


Queue

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.

2.Another common application of the deque is storing a software application's list of


undo operations.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 116


Faculty Video Links, Youtube & NPTEL
Video Links and Online Courses Details
• Self Made Video Link:
• Youtube/other Video Links

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 117


Daily Quiz

1. What is Stack and where it can be used?


2. What is a Queue, how it is different from stack and how is it
implemented?
3. What are Infix, prefix, Postfix notations?
4. How to implement a stack using queue?
5. How to implement a queue using stack?
6. What is recursion and when should you use it?
7. Write a function to copy string (Iterative and Recursive).
8. Check if a number is Palindrome using recursion
9. Reverse a stack using recursion.
10. Sort a stack using recursion.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 118


Assignment

Q 1 What do you understand by stable and in place sorting?

Q 2 Consider the following infix expression and convert into reverse polish
notation using stack. A + (B * C – (D / E ^ F) * H)

Q3 Recursive function to delete k-th node from linked list.

Q4. Write the C Program to implement queue using stack.

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.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 119


Assignment

Q7. What is tail recursion? Write recursive


function for tower of Hanoi problem and remove
tail recursion, if any, from it.
Q8. Write the algorithm for insertion in a
circular queue using array.
Q9. Define doubly ended queue.
Q10. Define Priority Queue.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 120


MCQ s

1. Process of inserting an element in stack is called ____________


a) Create
b) Push
c) Evaluation
d) Pop

2. Process of removing an element from stack is called __________


a) Create
b) Push
c) Evaluation
d) Pop

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 121


MCQ s
3. 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

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 122


MCQ s
5. Which of the following applications may use a stack?
a) A parentheses balancing program
b) Tracking of local variables at run time
c) Compiler Syntax Analyzer
d) Data Transfer between two asynchronous process

6. 1. Recursion is a method in which the solution of a problem depends


on ____________
a) Larger instances of different problems
b) Larger instances of the same problem
c) Smaller instances of the same problem
d) Smaller instances of different problems

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 123


MCQ s

7. Recursion is similar to which of the following?


a) Switch Case
b) Loop
c) If-else
d) if elif else

8. A queue follows __________


a) FIFO (First In First Out) principle
b) LIFO (Last In First Out) principle
c) Ordered array
d) Linear tree

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 124


MCQ s

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

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 125


Questions

Q1. What is Stack and where it can be used?


Q2. What is a Queue, how it is different from stack and how is it implemented?
Q3. What are Infix, prefix, Postfix notations?
Q4. How to implement a stack using queue?
Q5. How to implement a queue using stack?
Q6. What is recursion and when should you use it?
Q7. Write a function to copy string (Iterative and Recursive).
Q8. Check if a number is Palindrome using recursion
Q9. Reverse a stack using recursion.
Q10. Sort a stack using recursion.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 126


Glossary Questions

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 127


Glossary Questions

3. Which of the following applications may use a stack?

a) A parentheses balancing program

b) Tracking of local variables at run time

c) Compiler Syntax Analyzer

d) Data Transfer between two asynchronous process

4. Recursion is a method in which the solution of a problem depends on


____________

a) Larger instances of different problems

b) Larger instances of the same problem

c) Smaller instances of the same problem

d) Smaller instances of different problems


27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 128
Glossary Questions

5. Recursion is similar to which of the following?


a) Switch Case
b) Loop
c) If-else
d) if elif else

6. A queue follows __________


a) FIFO (First In First Out) principle
b) LIFO (Last In First Out) principle
c) Ordered array
d) Linear tree

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 129


Glossary Questions

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

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 130


Expected Questions for University Exam

Q1. Define priority queue.


Q2. Write a program in C for implementation of a queue. Your program
should at least contain ADD, CREATE. DELETE, FULL and EMPTY
functions.
Q3. If an array is defined as int a[10] [20] in C, devise a formula to
calculate the address of an any variable say a[i] [j], for any valid value
of i and j.
Q4. Write a program to implement STACK using linked list.
Q5. If the Tower of Hanoi is operated on n=10 disks, calculate the total
number of moves.
Q6. Differentiate between overflow and underflow condition in a
linked list.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 131


Expected Questions for University Exam
Q7. Convert the following infix expression into postfix expression:
B-C/D+A*(F-G/H).
Q8.Write a program in C to compute the factorial of given number
recursively.
Q9.Write a Program in C to implement all operations of a Stack using
array.
Q10.Define Dequeue.
Q11. Write the syntax to check whether a given circular queue is full or
empty?
Q12. What is Recursion? Give disadvantages of recursion.
Q13.Explain Tower of Hanoi problem and write a recursive algorithm
to solve it.
Q14. Explain how a circular queue can be implemented using arrays.
Write all functions for circular queue operations.
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 132
Last Year Question Paper

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 133


• https://noidainstituteofengtech-my.sharepoint.c
om/:f:/g/personal/meghagupta_cse_niet_co_in/
Ei2bmk_Sgj5PlJ_COtrbCwgBipzAb3Whgmh
MmcZkvf_JiQ?e=T4nfCV

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS 134


Unit -3
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 135
27/02/2024 Ms. Pragya Singh ACSE-0301 and DS 136
Unit -3
Last year Question Paper

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 137


Last year Question Paper

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 138


Last year Question Paper

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 139


References

[1] Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein,


“Data Structures Using C and C++”, PHI Learning Private Limited,
Delhi India
[2] Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia
Publications Pvt Ltd Delhi India.
[3] Lipschutz, “Data Structures” Schaum’s Outline Series, Tata
McGraw-hill Education (India) Pvt. Ltd.
[4] Thareja, “Data Structure Using C” Oxford Higher Education.
[5] AK Sharma, “Data Structure Using C”, Pearson Education India.

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 140


Thank you

27/02/2024 Ms. Pragya Singh ACSE-0301 and DS Unit -3 141

You might also like