c++ Syllabus Notes
c++ Syllabus Notes
B.Sc.
II Year III Sem
Latest 2022 Edition
DATA STRUCTURES
USING C++
Study Manual
FAQ’s and Important Questions
Short Question and Answers
Choose the Correct Answer
Fill in the blanks
Practical Programs
Solved Previous Question Papers
Solved Model Papers
9 /-
- by - `. 1 9
WELL EXPERIENCED LECTURER
TM
Rahul Publications
Hyderabad. Ph : 66550071, 9391018098
B.Sc.
II Year III Sem
(Osmania University)
DATA STRUCTURES
USING C++
Inspite of many efforts taken to present this book without errors, some errors
might have crept in. Therefore we do not take any legal responsibility for
such errors and omissions. However, if they are brought to our notice, they
will be corrected in the next edition.
Price ` 199-00
O Unit - I
Unit - II
1 - 88
89 - 180
N Unit - III
Unit - IV
181 - 274
275 - 336
N Model Paper - II
Model Paper - III
432 - 432
433 - 433
UNIT - I
Basic data Structure: Introduction to Data Structures, Types of Data Structures, and Introduction
to Algorithms, Pseudo code, and Relationship among data, data structures,andalgorithms,
Implementation of data structures, Analysis of Algorithms.
Stacks: Concept of Stacks and Queues, Stacks, Stack Abstract Data Type, Representation of
Stacks Using Sequential Organization (Arrays), Multiple Stacks, Applications of Stack, Expression
Evaluation and Conversion, Polish notation and expression conversion, Processing of Function
Calls, Reversing a String with a Stack, Recursion.
UNIT - II
Linked Lists: Introduction, Linked List, Linked List Abstract Data Type, Linked List Variants,
Doubly Linked List, Circular Linked List, Representation of Sparse Matrix Using Linked List,
Linked Stack, Linked Queue.
UNIT - III
Trees: Introduction, Types of Trees, Binary Tree, Binary Tree Abstract Data Type, Realization of
a Binary Tree, Insertion of a Node in Binary Tree, Binary Tree Traversal, Other Tree Operations,
Binary Search Tree, Threaded Binary Tree, Applications of Binary Trees.
Searching and Sorting: Search Techniques-Linear Search, Binary Search, Sorting
TechniquesSelection Sort, Bubble Sort, Insertion Sort, Merge Sort, Quick Sort, Comparison of
All Sorting Methods, Search Trees: Symbol Table, Optimal Binary Search Tree, AVL Tree
(Heightbalanced Tree).
UNIT - IV
Graphs: Introduction, Representation of Graphs, Graph Traversal – Depth First Search, Breadth
First Search, Spanning Tree, Prim’s Algorithm, Kruskal’s Algorithm.
Hashing: Introduction, Key Terms and Issues, Hash Functions, Collision Resolution Strategies,
Hash Table Overflow, Extendible Hashing
Heaps: Basic Concepts, Implementation of Heap, Heap as Abstract Data Type, Heap Sort, Heap
Applications.
Contents
UNIT - I
Topic Page No.
1.1 Basic Data Structures ........................................................................................................ 1
1.1.1 Introduction to data structures .............................................................................. 1
1.1.2 Types of data structures and Introduction to algorithm .......................................... 3
1.1.3 Pseudo code and Relationship among data, data structures and algorithms .......... 8
1.1.4 Implementation of data structures .......................................................................16
1.1.5 Analysis of Algorithms .........................................................................................17
1.2 Stacks .................................................................................................................. 26
1.2.1 Concepts of Stacks and Queues, Stacks, Stack Abstract Data type ...................... 26
1.2.2 Representation of Stacks Using sequential organizations(Arrays) ......................... 30
1.2.3 Multiple Stack ...................................................................................................... 35
1.2.4 Applications of Stack, Expression evaluation and conversion, polish notation
and Expression convertion ..................................................................................38
1.2.5 Processing of Function calls .................................................................................65
1.2.6 Reversing a string with stack ................................................................................67
1.2.7 Recursion ............................................................................................................ 69
Short Question & Answers ...................................................................................... 71 - 84
Choose the Correct Answers ................................................................................... 85 - 86
Fill in the blanks ...................................................................................................... 87 - 87
One Mark Answers .................................................................................................. 88 - 88
UNIT - II
2.1 Recursion .................................................................................................................. 89
2.1.1 Introduction ........................................................................................................ 89
2.1.2 Recurrence .......................................................................................................... 94
2.1.3 Use of Stack in Recursion ....................................................................................95
2.1.4 Variants of Recursion , Recursive functions ..........................................................97
2.1.5 Iteration Versus Recrusion .................................................................................101
2.2 Queues ................................................................................................................102
2.2.1 Concept of Queues, Queue Abstract Data Type ................................................102
2.2.2 Realization of Queues using Arrays ....................................................................106
I
Topic Page No.
2.2.3 Circular Queue, Multi Queues ...........................................................................112
2.2.4 Dequeue, Priority Queue ..................................................................................116
2.2.5 Applications of Queues ......................................................................................124
2.3 Linked List ................................................................................................................125
2.3.1 Introduction to Linked List ................................................................................125
2.3.2 Linked List Abstract Data Type ..........................................................................134
2.3.3 Liked List variants, Doubly Linked List, Circular Linked List. .............................137
2.3.4 Representation of Sparse Matrix using Linked List ............................................156
2.3.5 Linked Stack , Linked Queue ............................................................................158
Short Question & Answers .................................................................................. 165 - 177
Choose the Correct Answers ............................................................................... 178 - 178
Fill in the blanks .................................................................................................. 179 - 179
One Mark Answers .............................................................................................. 189 - 180
UNIT - III
3.1 Trees ................................................................................................................181
3.1.1 Introduction ......................................................................................................181
3.1.2 Types of Trees ....................................................................................................186
3.1.3 Binary Tree .......................................................................................................188
3.1.4 Binary Tree Abstract Data Type .........................................................................190
3.1.5 Realization of a Binary Tree ...............................................................................191
3.1.6 Insertion of a Node in Binary Tree ....................................................................196
3.1.7 Binary Tree Traversal .........................................................................................198
3.1.8 Other Tree Operations ......................................................................................201
3.1.9 Binary Search Tree ............................................................................................204
3.1.10 Threaded Binary Tree .......................................................................................215
3.1.11 Applications of Binary Trees. .............................................................................220
3.2 Searching and Sorting ...................................................................................................221
3.2.1 Search Techniques .............................................................................................221
3.2.1.1 Linear Search ......................................................................................222
3.2.1.2 Binary Search ......................................................................................224
3.2.2 Sorting Techniques ............................................................................................227
3.2.2.1 Selection Sort ......................................................................................227
II
Topic Page No.
3.2.2.2 Bubble Sort .........................................................................................230
3.2.2.3 Insertion Sort .......................................................................................232
3.2.2.4 Merge Sort ...........................................................................................235
3.2.2.5 Quick Sort ...........................................................................................236
3.2.3 Comparison of All Sorting Methods ..................................................................240
3.3 Search Trees ................................................................................................................242
3.3.1 Symbol Table ....................................................................................................242
3.3.2 Optimal Binary Search Tree ..............................................................................243
3.3.3 AVL Tree (Heightbalanced Tree) .......................................................................249
Short Question & Answers .................................................................................. 264 - 271
Choose the Correct Answers ............................................................................... 272 - 272
Fill in the blanks .................................................................................................. 273 - 273
One Mark Answers .............................................................................................. 274 - 274
UNIT - IV
4.1 Graphs ................................................................................................................275
4.1.1 Introduction ......................................................................................................275
4.1.2 Representation of Graphs .................................................................................276
4.2 Graph Traversal ............................................................................................................278
4.2.1 Depth First Search .............................................................................................278
4.2.2 Breadth First Search ..........................................................................................283
4.3 Spanning Tree ...............................................................................................................288
4.3.1 Prim’s Algorithm ...............................................................................................292
4.3.2 Kruskal’s Algorithm. ..........................................................................................296
4.4 Hashing ................................................................................................................300
4.4.1 Introduction ......................................................................................................300
4.4.2 Key Terms and Issues ........................................................................................301
4.4.3 Hash Functions ..................................................................................................301
4.4.4 Collision Resolution Strategies ...........................................................................304
4.4.5 Hash Table Overflow .........................................................................................310
4.4.6 Extendible Hashing ...........................................................................................310
III
Topic Page No.
4.5 Heaps ................................................................................................................312
4.5.1 Basic Concepts ..................................................................................................312
4.5.2 Implementation of Heap ...................................................................................317
4.5.2 Heap as Abstract Data Type ..............................................................................318
4.5.3 Heap Sort .........................................................................................................320
4.5.4 Heap Applications .............................................................................................327
Short Question & Answers .................................................................................. 328 - 333
Choose the Correct Answers ............................................................................... 334 - 334
Fill in the blanks .................................................................................................. 335 - 335
One Mark Answers .............................................................................................. 336 - 336
IV
FAQ’s & IMPORTANT QUESTIONS DATA STRUCTURES USING C++
UNIT - I
1. Define an algorithm. Write a flow chart and a pseudo code to compute the sum of the
first N natural numbers.
V
Rahul Publications
B.Sc. II YEAR III SEMESTER
UNIT - II
1. Explain Towers of Hanoi using recursion.
UNIT - III
VI
Rahul Publications
FAQ’s & IMPORTANT QUESTIONS DATA STRUCTURES USING C++
Ans : (Nov.-17)
Refer Unit-III, Q.No. 14
5. Explain Binary Search with an example.
Ans : (Junly-2019)
Refer Unit-III, Q.No. 23
6. Explain Selection Sort with an example.
UNIT - IV
1. What are the various ways to represent graphs?
VII
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans : (June-18)
Refer Unit-IV, Q.No. 3
3. Explain about BFS algorithm with an example.
Ans : (Imp.)
Ans : (Imp.)
VIII
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
tio
task for a programmer. Following terminology is
data so that it can be used efficiently.The data
structure name indicates itself that organizing the used as far as data structures are concerned.
data in memory. There are many ways of organizing
the data in the memory as we have already seen
Data
l i c a
one of the data structures, i.e., array in C language.
u
Array is a collection of memory elements in which b Data can be defined as an elementary value
or the collection of values, for example, student’s
ul P
data is stored sequentially, i.e., one after another.
In other words, we can say that array stores the
name and its id are the data about the student.
h
elements in a continuous manner. This organization Group Items
R a
of data is done with the help of an array of data
structures. There are also other ways to organize
the data in memory.
Data items which have subordinate data items
are called Group item, for example, name of a
student can have first name and the last name.
The major or the common operations that can be
performed on the data structures are:
Record
Searching: We can search for any element
in a data structure. Record can be defined as the collection of
various data items, for example, if we talk about
Sorting: We can sort the elements of a data
structure either in an ascending or descending the student entity, then its name, address, course
order. and marks can be grouped together to form the
Insertion: We can also insert the new record for the student.
element in a data structure. File
Updation: We can also update the element,
A File is a collection of various records of one
i.e., we can replace the element with another
element. type of entity, for example, if there are 60
employees in the class, then there will be 20 records
Deletion: We can also perform the delete
operation to remove the element from the in the related file where each record contains the
data structure. data about each employee.
1
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Consider an inventory size of 106 items in a store, If our application needs to search for a particular
Multiple requests
c a tio
item, it needs to traverse 106 items every time, results in slowing down the search process.
b l i
If thousands of users are searching the data simultaneously on a web server, then there are the
P u
chances that a very large server can be failed during that process.
In order to solve the above problems, data structures are used. Data is organized to form a data
instantly.
a h ul
structure in such a way that all items are not required to be searched and required data can be searched
Ans :
Efficiency
R
Q4. List and explain advantages of data structures ?
Efficiency of a program depends upon the choice of data structures. For example: suppose, we
have some data and we need to perform the search for a perticular record. In that case, if we organize our
data in an array, we will have to search sequentially element by element. hence, using array may not be
very efficient here. There are better data structures which can make the search process efficient like
ordered array, binary search tree or hash tables.
Reusability
Data structures are reusable, i.e. once we have implemented a particular data structure, we can use
it at any other place. Implementation of data structures can be compiled into libraries which can be used
by different clients.
Abstraction
Data structure is specified by the ADT which provides a level of abstraction. The client program uses
the data structure through interface only, without getting into the implementation details.
2
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Ans :
n s
c a tio
b l i
P u
ul
Linear Data Structures
h
A data structure is called linear if all of its elements are arranged in the linear order. In linear data
R a
structures, the elements are stored in non-hierarchical way where each element has the successors and
predecessors except the first and last element.
Types of Linear Data Structures are given below:
Arrays
An array is a collection of similar type of data items and each data item is called an element of the
array. The data type of the element may be any valid data type like char, int, float or double.
The elements of array share the same variable name but each one carries a different index number
known as subscript. The array can be one dimensional, two dimensional or multidimensional.
The individual elements of the array age are:
age[0], age[1], age[2], age[3],......... age[98], age[99].
Linked List
Linked list is a linear data structure which is used to maintain a list in the memory. It can be seen as
the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a
pointer to its adjacent node.
Stack
Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
3
Rahul Publications
B.Sc. II YEAR III SEMESTER
A stack is an abstract data type (ADT), can be Q6. What is Algorithm? What are the
implemented in most of the programming characteristics of an algorithm ?
languages. It is named as stack because it behaves
like a real-world stack, for example: - piles of plates
Ans :
or deck of cards etc. An algorithm is a process or a set of rules
Queue required to perform calculations or some other
problem-solving operations especially by a
Queue is a linear list in which elements can computer. The formal definition of an algorithm is
be inserted only at one end called rear and deleted that it contains the finite set of instructions which
only at the other end called front. are being carried in a specific order to perform the
It is an abstract data structure, similar to stack. specific task. It is not the complete program or code;
Queue is opened at both end therefore it follows it is just a solution (logic) of a problem, which can
First-In-First-Out (FIFO) methodology for storing be represented either as an informal description
the data items. using a Flowchart or Pseudo code.
Non Linear Data Structures The following are the characteristics of an
This data structure does not form a sequence algorithm:
i.e. each item or element is connected with two or Input
n s
tio
more other items in a non-linear arrangement. The
An algorithm has some input values. We can
data elements are not arranged in sequential
structure.
Types of Non Linear Data Structures are given
l i c a
pass 0 or some input value to an algorithm.
Output
below:
ul P
Trees are multilevel data structures with a
algorithm.
Unambiguity
a h
hierarchical relationship among its elements known
as nodes. The bottommost nodes in the herierchy
An algorithm should be unambiguous which
means that the instructions in an algorithm
R
are called leaf node while the topmost node is
called root node. Each node contains pointers to
point adjacent nodes.
should be clear and simple.
Finiteness
Tree data structure is based on the parent- An algorithm should have finiteness. Here,
child relationship among the nodes. Each node in finiteness means that the algorithm should
the tree can have more than one children except contain a limited number of instructions, i.e.,
the leaf nodes whereas each node can have atmost the instructions should be countable.
one parent except the root node. Trees can be Effectiveness
classfied into many categories which will be discussed
later in this tutorial. An algorithm should be effective as each
instruction in an algorithm affects the overall
Graphs process.
Graphs can be defined as the pictorial Language independent
representation of the set of elements (represented
by vertices) connected by the links known as edges. An algorithm must be language-independent
A graph is different from tree in the sense that a so that the instructions in an algorithm can
graph can have cycle while the tree can not have be implemented in any of the languages with
the one. the same output.
4
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Q7. Why do we need algorithms ? List out The following are the steps required to
the characteristics of an algorithm. add two numbers entered by the user:
Step 1: Start
Ans :
Step 2: Declare three variables a, b, and sum.
We need algorithms because of the following
Step 3: Enter the values of a and b.
reasons:
Step 4: Add the values of a and b and store the
Scalability result in the sum variable, i.e., sum=a+b.
It helps us to understand the scalability. When Step 5: Print sum
we have a big real-world problem, we need Step 6: Stop
to scale it down into small-small steps to easily
Characteristics of an Algorithm
analyze the problem.
Unambiguous
Performance
Algorithm should be clear and unambiguous.
The real-world is not easily broken down into Each of its steps (or phases), and their inputs/
smaller steps. If the problem can be easily outputs should be clear and must lead to only
broken into smaller steps means that the one meaning.
problem is feasible.
Let’s understand the algorithm through a real-
Input
n s
tio
An algorithm should have 0 or more well-
world example. Suppose we want to make a lemon defined inputs.
juice, so following are the steps required to make a
lemon juice:
l i c a
Output
An algorithm should have 1 or more well-
Step 1: First, we will cut the lemon into half.
ul P
Step 2: Squeeze the lemon as much you can and
take out its juice in a container.
Step 3: Add two tablespoon sugar in it.
desired output.
Finiteness
a h
Step 4: Stir the container until the sugar gets
Algorithms must terminate after a finite
number of steps.
dissolved.
R
Step 5: When sugar gets dissolved, add some water
and ice in it.
Feasibility
Should be feasible with the available
resources.
5
Rahul Publications
B.Sc. II YEAR III SEMESTER
tio
importance of designing an algorithm:
Robustness
Robustness means that how an algorithm can
clearly define our problem.
l i c a
Brute force algorithm
The general logic structure is applied to design
User-friendly
u b an algorithm. It is also known as an exhaustive
search algorithm that searches all the
ul P
If the algorithm is not user-friendly, then the
designer will not be able to explain it to the
programmer.
possibilities to provide the required solution.
Such algorithms are of two types:
Simplicity
a h 1. Optimizing: Finding all the solutions
of a problem and then take out the best
understand. R
If the algorithm is simple then it is easy to
solution or if the value of the best
solution is known then it will terminate
if the best solution is known.
Extensibility 2. Sacrificing: As soon as the best
If any other algorithm designer or progra- solution is found, then it will stop.
mmer wants to use your algorithm then it Divide and conquer
should be extensible.
It is a very implementation of an algorithm. It
Q9. Explain Importance, Issues and allows you to design an algorithm in a step-
approaches of an algorithm? by-step variation. It breaks down the
algorithm to solve the problem in different
Ans :
methods. It allows you to break down the
Importance of Algorithms problem into different methods, and valid
output is produced for the valid input. This
1. Theoretical importance
valid output is passed to some other function.
When any real-world problem is given to us
and we break the problem into small-small Greedy algorithm
modules. To break down the problem, we It is an algorithm paradigm that makes an
should know all the theoretical aspects. optimal choice on each iteration with the
6
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
hope of getting the best solution. It is easy to Q10. List out major categories of algorithms.
implement and has a faster execution time.
But, there are very rare cases in which it
Ans :
provides the optimal solution. The major categories of algorithms are given
Dynamic programming below:
It makes the algorithm more efficient by Sort: Algorithm developed for sorting the
storing the intermediate results. It follows five items in a certain order.
different steps to find the optimal solution for Search: Algorithm developed for searching
the problem: the items inside a data structure.
1. It breaks down the problem into a Delete: Algorithm developed for deleting
subproblem to find the optimal solution. the existing element from the data structure.
2. After breaking down the problem, it
Insert: Algorithm developed for inserting an
finds the optimal solution out of these
item inside a data structure.
subproblems.
Update: Algorithm developed for updating
3. Stores the result of the subproblems is
known as memorization. the existing element inside a data structure.
Q11. Explain how algorithms are analysed?
4. Reuse the result so that it cannot be
recomputed for the same subproblems. Ans :
n s
tio
5. Finally, it computes the result of the The algorithm can be analyzed in two levels,
complex program.
Branch and Bound Algorithm
i c a
i.e., first is before creating the algorithm, and second
is after creating the algorithm. The following are the
l
two analysis of an algorithm:
The branch and bound algorithm can be
applied to only integer programming
u b
Priori Analysis
ul P
problems. This approach divides all the sets
of feasible solutions into smaller subsets. These
subsets are further evaluated to find the best
Here, priori analysis is the theoretical analysis
of an algorithm which is done before
implementing the algorithm. Various factors
solution.
R
Randomized Algorithm
As we have seen in a regular algorithm, we
have predefined input and required output.
Those algorithms that have some defined set
algorithm like processor speed, which has no
effect on the implementation part.
Posterior Analysis
Here, posterior analysis is a practical analysis
of inputs and required output, and follow
of an algorithm. The practical analysis is
some described steps are known as
achieved by implementing the algorithm using
deterministic algorithms. What happens that
any programming language. This analysis
when the random variable is introduced in
basically evaluate that how much running
the randomized algorithm?. In a randomized
time and space taken by the algorithm.
algorithm, some random bits are introduced
by the algorithm and added in the input to The performance of the algorithm can be
produce the output, which is random in measured in two factors:
nature. Randomized algorithms are simpler Time complexity
and efficient than the deterministic algorithm.
The time complexity of an algorithm is the
Backtracking amount of time required to complete the
Backtracking is an algorithmic technique that execution. The time complexity of an
solves the problem recursively and removes algorithm is denoted by the big O notation.
the solution if it does not satisfy the constraints Here, big O notation is the asymptotic
of a problem. notation to represent the time complexity.
7
Rahul Publications
B.Sc. II YEAR III SEMESTER
The time complexity is mainly calculated by 1.1.3 Pseudo code and Relationship among
counting the number of steps to finish the data, data structures and algorithms
execution. Let’s understand the time Q12. What is pseudo code? Explain with an
complexity through an example. example. List out its advantages and
sum=0; disadvantages?
// Suppose we have to calculate Ans :
the sum of n numbers. Pseudocode is not a programming language,
for i=1 to n it is a simple way of describing a set of instructions
sum=sum+i; that does not have to use specific syntax.
// when the loop ends then sum Writing in pseudocode is similar to writing in
a programming language. Each step of the algorithm
holds the sum of the n numbers
is written on a line of its own in
return sum; sequence. Usually, instructions are written in
In the above code, the time complexity of uppercase, variables in lowercase and messages in
the loop statement will be atleast n, and if the value sentence case.
of n increases, then the time complexity also In pseudocode, INPUT asks a question.
increases. While the complexity of the code, i.e.,
return sum will be constant as its value is not s
OUT PUT prints a message on screen.
n
tio
Pseudocode is an informal way of
dependent on the value of n and will provide the
programming description that does not require any
result in one step only. We generally consider the
worst-time complexity as it is the maximum time
taken for any given input size.
l i c a
strict programming language syntax or underlying
technology considerations. It is used for creating an
Space complexity
u b
outline or a rough draft of a program. Pseudocode
summarizes a program’s flow, but excludes
P
An algorithm’s space complexity is the
ul
amount of space required to solve a problem
and produce an output. Similar to the time
underlying details. System designers write
pseudocode to ensure that programmers
understand a software project’s requirements and
a h
complexity, space complexity is also expressed
in big O notation.
align code accordingly.
It is written in the form of annotations and
R
For an algorithm, the space is required for
the following purposes:
1. To store program instructions
informational text that is written in plain English only.
Just like programming languages, it doesn’t have
any syntax, so it cannot be compiled or interpreted
by the compiler.
2. To store constant values Below are some points which we need to keep
3. To store variable values in mind while designing the pseudocode
4. To track the function calls, jumping We should have to use the appropriate
statements, etc. naming convention. By doing that, it is very
Auxiliary space easy to understand the pseudocode. So, the
naming should be simple and distinct.
The extra space required by the algorithm,
excluding the input size, is known as an auxiliary We should have to use the appropriate
space. The space complexity considers both the sentence casings. For methods, we use the
spaces, i.e., auxiliary space, and space used by the CamelCase, for constants, we use the upper
input. case, and for variables, we use the lower case.
So, The pseudocode should not be abstract, and
Space complexity = Auxiliary space + Input the thing which is going to happen in the
size. actual code should be elaborated.
8
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
We use the ‘if-then, ‘for’, ‘while’, ‘cases’ 5. Find a reminder of n by using n%10.
standard programming structures in the same 6. Remove the last digit from the number by
way as we use it in programming. using n/10.
All the sections of the pseudocode should be 7. Find the thrice of the reminder and add it to
completed, finite and clear to understand. c.
The pseudocode should be as simple as it can 8. If temp == c
be understood by a layman having no
Print “Armstrong number”
sufficient knowledge of technical terms. So,
we don’t write the pseudocode in a complete 9. else
programmatic manner. Not an Armstrong number”
Pseudocode is also written using some specific The algorithm of the above program can be
words and characters, which are shown below: written in the following way:
To begin the comment double forward slash Input the number.
are used “//”.
1. Initialize c = 0 and temp = n.
Matching braces “{and}” are used to present
2. Repeat until (temp != 0)
blocks where a compound statement (set of
simple statements) can be illustrated as a 3.
n s
a = temp % 10 //remainder
tio
block and terminated by a semicolon”;”. The 4. c = c + (a * a * a)
body of a procedure constructs a block as
well.
All the identifiers start with a letter and the
5.
6.
l i a
temp = temp / 10
c
if (c == n)
datatype of the variables are not declared
b
Pu
7. Display “Armstrong number”
explicitly.
8. Else
ul
An assignment statement is used for the
assigning values to the variables.
9. Display “Not an Armstrong number”
ah
Advantages
To produce the boolean values (i.e., true and
R
false) the logical operators and, or and not
and the relational operators <, d”, =, =,
e” and > are provided.
In order to improve the readability of any
approach, pseudo code plays a very
important role.
Input and output are presented by read and In between the program and the algorithm,
write instructions. Pseudo code work as a bridge. It is treated as
a document so that the developer can
“if and then” expressions are used to express understand the program easily.
a conditional statement.
Pseudo code focuses on explaining the
Example:
working on each line of the program. Due to
The pseudo code of the Armstrong number this, it is very easy for the programmer to
can be written in the following way: construct the code.
1. Initialize c to zero. Disadvantages
2. Initialize n to a random number to check The visual representation of the programming
Armstrong. code can be easily understood, and the
3. Initialize temp to n. pseudocode doesn’t provide it.
4. Repeat steps until the value of n are greater There is no well-defined format to write the
than zero. pseudocode.
9
Rahul Publications
B.Sc. II YEAR III SEMESTER
There are no standards available for pseudocode. Companies use their own standards to write it.
If we use pseudocode, we need to maintain one more document for our code.
Q13. Write a Pseudo code and algorithm for calculating area of circle.
Ans :
Code:
AreaofCircle()
{
BEGIN
Read: Number radius, Area;
Input r;
Area = 3.14 * r * r;
Output Area;
END
n s
tio
}
Algorithm:
1. Start.
l i c a
2.
b
Read the radius value r as the input given by the user.
u
3.
4. Display the Area.
ul P
Calculate the area as Area: 3.14 * r * r.
5. End.
a h
Ans :
R
Q14. Write an algorithm to determine if a student is pass or fail based on the grades. Grades
are the average of total marks obtained in all the subjects.
Algorithm
Steps are given below:
1. Start
2. Input Marks1, Marks2, Marks3, Marks4
3. Grade= (Marks1+Marks2 +Marks3 + Marks4)/4
4. If (Grade<50) then
5. Print “Fail”
6. Else
7. Print “Pass”
8. End if
9. Stop
10
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Q15. Define an algorithm. Write a flow chart and a pseudo code to compute the sum of the
first N natural numbers.
n s
c a tio
b l i
P u
a h ul
R
Pseudo code for some of N natural numbers
BEGIN
NUMBER counter, sum=0
FOR counter=1 TO 100 STEP 1 DO
sum=sum+counter
ENDFOR
OUTPUT sum
END
11
Rahul Publications
B.Sc. II YEAR III SEMESTER
l i c a
Ans :
b
S. NO
1.
Pseudocode
ul Pu
It is the method used for writing
Algorithm
It is another method of describing the
ah
the computer program in easy ad computer program in a readable ad under
R
readable format or in the English
language to make it the user or
developer easier to understand the
standable with the sequence of steps written
to follow while writing the code.
12
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
a
Algorithms can be used in any complex
complicated programming languages
b l i
programming language as it uses simple
P u
as algorithms because it is widely used
when the combination of programming
logical code snippets sometimes which is
more than natural language as used
a h ul
and simple natural languages is required
for constructing the pseudocode.
in Pseudocode constructions.
9.
R
The pseudocode also uses few specific
words or phrases or special symbols
to differentiate it from the algorithm,
The algorithm is written using some
specific criteria such as it includes input
statement, output statement, also includes
though pseudocodes can be considered with effectiveness and efficiency of the
as a method of writing algorithms. It algorithm code written for a particular program,
includes a forward slash for beginning clear statements which are free from
comments, uses flower braces for in- ambiguity, also includes certain or proper
cluding logical blocks, italso uses some conditions to be displayed for correctly
operators to specify the logic of the code. terminating after few steps when required
in the code, and sometimes small logical
codes can also be written to specify some
logic directly.
10. Pseudocode cannot be considered Algorithms can be considered as
algorithms. pseudocode.
13
Rahul Publications
B.Sc. II YEAR III SEMESTER
Q18. What is flow chart? Discuss various symbols used in flow chart representation.
Ans :
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts
use simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol Symbol Name Purpose
Start/Stop Used at the beginning and end of the
algorithm to show start and end of the program.
Input/ Output
s
Used for denoting program inputs and outputs.
n
c a tio
Decision
b l i
Stands for decision statements in a program,
where answer is usually Yes or No.
P u
ul
Arrow Shows relationships between different shapes.
a h
R On-page Connector Connects two or more parts of a flowchart,
which are on the same page.
14
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
c a tio
b l
Q20. List out the advantages and disadvantages of flow charts
i
Ans :
P u
ul
Advantages
Communication
a h
Flowcharts are better way of communicating the logic of a system to all concerned.
Effective analysis
R
With the help of flowchart, problem can be analysed in more effective way.
Proper documentation
Program flowcharts serve as a good program documentation, which is needed for various purposes.
Efficient Coding
The flowcharts act as a guide or blueprint during the systems analysis and program development
phase.
Proper Debugging: The flowchart helps in debugging process.
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.
Disadvanatges
Although a flowchart is a very useful tool, there are a few limitations in using flowcharts which are
listed below:
15
Rahul Publications
B.Sc. II YEAR III SEMESTER
Complex logic
Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and
clumsy.
Alterations and Modifications
If alterations are required the flowchart may require re-drawing completely.
Reproduction
As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
The essentials of what is done can easily be lost in the technical details of how it is done.
Q21. What are the differences between algorithm and flow chart.
Ans :
Flowchart Algorithm
Block by block information Step by step instruction representing the
diagram representing the data flow. process of any solution.
It is a pictorial representation of a process.
n s
It is a stepwise analysis of the work to be done.
tio
The solution is shown in a graphical format. The solution is shown in a non-computer
c
It is somewhat difficult to understand.
b
Pu
algorithm.
Easy to show branching and looping. Difficult to show branching and looping
ul
Flowchart for a big problem is impractical The algorithm can be written for any problem
ah
Difficult to debug errors. Easy to debug errors.
R
It is easy to make a flowchart. It is difficult to write an algorithm as compared
to a flowchart.
1.1.4 Implementation of data structures
Q22. Discuss possible ways to implement data structures.
Ans :
Data structures are implemented by using
1. Arrays
2. Linked list
3. Stack
4. Queue
1. Arrays
An array is a structure of fixed-size, w hich can hold items of the same data type. Arrays are
indexed, meaning that random access is possible. An array is usually presented as a native data
structure in many programming languages.
16
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
s
are the same. For example, we know that a set of
n
numbers can be sorted using different algorithms.
tio
A stack is a LIFO (Last In First Out - the
element placed at last can be accessed at first) Number of comparisons performed by one
structure. Although this data structure has a
different behaviour, this can be considered
l i c a
algorithm may vary with others for the same input.
Hence, time complexity of those algorithms may
differ. At the same time, we need to calculate the
as a derivation of the linked list with only
b
Pu
memory space required by each algorithm.
a head or access to the top element.
Analysis of algorithm is the process of analyzing
4. Queues
ah
terms of the time and size required (the size of
A queue is a FIFO (First In First Out - the
memory for storage while implementation).
element placed at first can be accessed at first)
R
structure. This can be considered as the
reverse scenario of the stack. In simpler terms,
it is a linked list where we add from one end
However, the main concern of analysis of algorithms
is the required time or performance. Generally, we
perform the following types of analysis -
Worst-case
read from the other end.
The maximum number of steps taken on any
1.1.5 Analysis of Algorithms instance of size a.
Q23. Explain how algorithms are analysed. Best-case
Ans : The minimum number of steps taken on any
In theoretical analysis of algorithms, it is instance of size a.
common to estimate their complexity in the
Average case
asymptotic sense, i.e., to estimate the complexity
function for arbitrarily large input. The An average number of steps taken on any
term ”analysis of algorithms” was coined by Donald instance of size a.
Knuth.
Amortized
Algorithm analysis is an important part of
computational complexity theory, which provides A sequence of operations applied to the input
theoretical estimation for the required resources of of size a averaged over time.
17
Rahul Publications
B.Sc. II YEAR III SEMESTER
Q24. What is time complexity ? Explain how to calculate time complexity with an example.
Ans :
Time complexity of an algorithm signifies the total time required by the program to run till its
completion.
The time complexity of algorithms is most commonly expressed using the big O notation. It’s an
asymptotic notation to represent the time complexity.Time Complexity is most commonly estimated by
counting the number of elementary steps performed by any algorithm to finish execution.
Calculating Time Complexity
the most common metric for calculating time complexity is Big O notation. This removes all constant
factors so that the running time can be estimated in relation to N, as N approaches infinity. In general you
can think of it like this :
statement;
Above we have a single statement. Its Time Complexity will be Constant. The running time of the
statement will not change in relation to N.
for(i=0; i< N; i++)
{
n s
statement;
}
c a tio
b l i
The time complexity for the above algorithm will be Linear. The running time of the loop is directly
{
for(j=0; j <N;j++)
a h ul
{
statement;
}
R
}
This time, the time complexity for the above code will be Quadratic. The running time of the two
loops is proportional to the square of N. When N doubles, the running time increases by N * N.
while(low <= high)
{
mid=(low + high)/2;
if(target < list[mid])
high= mid -1;
elseif(target > list[mid])
low= mid +1;
18
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
elsebreak;
}
This is an algorithm to break a set of numbers into halves, to search a particular field(we will study
this in detail later). Now, this algorithm will have a Logarithmic Time Complexity. The running time of
the algorithm is proportional to the number of times N can be divided by 2(N is high-low here). This is
because the algorithm divides the working area in half with each iteration.
voidquicksort(int list[],int left,int right)
{
int pivot =partition(list, left, right);
quicksort(list, left, pivot -1);
quicksort(list, pivot +1, right);
}
Types of Notations for Time Complexity
s
Now we will discuss and understand the various notations used for Time Complexity.
n
tio
1. Big Oh denotes “fewer than or the same as” <expression> iterations.
2. Big Omega denotes “more than or the same as” <expression> iterations.
3.
i
Big Theta denotes “the same as” <expression> iterations.
l c a
4.
5.
u b
Little Oh denotes “fewer than” <expression> iterations.
Little Omega denotes “more than” <expression> iterations.
ul P
O(expression) is the set of functions that grow slower than or at the same rate as expression. It
indicates the maximum required by an algorithm for all input values. It represents the worst case of an
h
algorithm’s time complexity.
a
R
Omega (expression) is the set of functions that grow faster than or at the same rate as expression.
It indicates the minimum time required by an algorithm for all input values. It represents the best case of
an algorithm’s time complexity.
Theta(expression) consist of all the functions that lie in both O(expression) and Omega(expression).
It indicates the average bound of an algorithm. It represents the average case of an algorithm’s time
complexity.
Q25. What is space complexity? Explain with an example.
Ans :
Space complexity is an amount of memory used by the algorithm (including the input values of the
algorithm), to execute it completely and produce the result.
We know that to execute an algorithm it must be loaded in the main memory. The memory can be
used in different forms:
Variables (This includes the constant values and temporary values)
Program Instruction
Execution
19
Rahul Publications
B.Sc. II YEAR III SEMESTER
Auxiliary Space
Auxiliary space is extra space or temporary space used by the algorithms during its execution.
Memory Usage during program execution
Instruction Space is used to save compiled instruction in the memory.
Environmental Stack is used to storing the addresses while a module calls another module or
functions during execution.
Data space is used to store data, variables, and constants which are stored by the program and it is
updated during execution.
Space Complexity = Auxiliary Space + Input space
While executing, algorithm uses memory space for three reasons:
1. Instruction Space
It’s the amount of memory used to save the compiled version of instructions.
2. Environmental Stack
n s
Sometimes an algorithm(function) may be called inside another algorithm(function). In such a
situation, the current variables are pushed onto the system stack, where they wait for further execution
tio
and then the call to the inside algorithm(function) is made.
i a
For example, If a function A() calls function B() inside it, then all th variables of the
c
function A() will get stored on the system stack temporarily, while the function B() is called and
l
3.
executed inside the funciton A().
Data Space
u b
ul P
Amount of space used by the variables and constants.
But while calculating the Space Complexity of any algorithm, we usually consider only Data
a h
Space and we neglect the Instruction Space and Environmental Stack.
R
For calculating the space complexity, we need to know the value of memory used by different type
of datatype variables, which generally varies for different operating systems, but the method for
calculating the space complexity remains the same.
Type Size
bool, char, unsigned char, signed char, __int8 1 byte
__int16, short, unsigned short, wchar_t, __wchar_t 2 bytes
float, __int32, int, unsigned int, long, unsigned long 4 bytes
double, __int64, long double, long long 8 bytes
Now let’s learn how to compute space complexity by taking a few examples:
{
int z = a + b + c;
return(z);
20
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
}
In the above expression, variables a, b, c and z are all integer types, hence they will take up 4
bytes each, so total memory requirement will be (4(4) + 4) = 20 bytes, this additional 4 bytes is for return
value. And because this space requirement is fixed for the above example, hence it is called Constant
Space Complexity.
Let’s have another example, this time a bit complex one,
intsum(int a[], int n)
{
int x = 0; // 4 bytes for x
for(inti = 0; i< n; i++) // 4 bytes for i
{
x = x + a[i];
}
return(x);
n s
}
c a tio
4 bytes each for x, n, i and the return value.
b l i
In the above code, 4*n bytes of space is required for the array a[] elements.
P u
Hence the total memory requirement will be (4n + 12), which is increasing linearly with the increase
ul
in the input value n, hence it is called as Linear Space Complexity.
a h
Similarly, we can have quadratic and other complex space complexity as well, as the complexity of
an algorithm increases.
R
But we should always focus on writing algorithm code in such a way that we keep the space
complexity minimum.
Q26. What is the use of asymptotic analysis?
Ans :
Using asymptotic analysis, we can get an idea about the performance of the algorithm based on the
input size. We should not calculate the exact running time, but we should find the relation between the
running time and the input size. We should follow the running time when the size of input is increased.
For the space complexity, our goal is to get the relation or function that how much space in the
main memory is occupied to complete the algorithm.
Asymptotic Behavior
For a function f(n) the asymptotic behavior is the growth of f(n) as n gets large. Small input values
are not considered. Our task is to find how much time it will take for large value of the input.
For example, f(n) = c * n + k as linear time complexity. f(n) = c * n2 + k is quadratic time
complexity.
21
Rahul Publications
B.Sc. II YEAR III SEMESTER
The analysis of algorithms can be divided into three different cases. The cases are as follows -
Best Case - Here the lower bound of running time is calculated. It describes the behavior of
algorithm under optimal conditions.
Average Case - In this case we calculate the region between upper and lower bound of the
running time of algorithms. In this case the number of executed operations are not minimum and not
maximum.
Worst Case - In this case we calculate the upper bound of the running time of algorithms. In this
case maximum number of operations are executed.
n s
c a tio
b l i
P u
a h ul
Q27. Discuss in detail asymptotic notaions.
Ans :
R
The commonly used asymptotic notations used for calculating the running time complexity of an
algorithm is given below:
• Big oh Notation (?)
• Omega Notation ()
• Theta Notation ()
Big oh Notation (O)
Big O notation is an asymptotic notation that measures the performance of an algorithm by simply
providing the order of growth of the function.
This notation provides an upper bound on a function which ensures that the function never grows
faster than the upper bound. So, it gives the least upper bound on a function so that the function
never grows faster than this upper bound.
It is the formal way to express the upper boundary of an algorithm running time. It measures the
worst case of time complexity or the algorithm’s longest amount of time to complete its operation. It is
represented as shown below:
22
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
For example:
If f(n) and g(n) are the two functions defined for positive integers, then f(n) = O(g(n)) as f(n)
is big oh of g(n) or f(n) is on the order of g(n)) if there exists constants c and no such that:
f(n)d c.g(n) for all n no
n s
tio
This implies that f(n) does not grow faster than g(n), or g(n) is an upper bound on the function f(n).
In this case, we are calculating the growth rate of the function which eventually calculates the worst time
c
Example 1: f(n)=2n+3 , g(n)=n
u b
Now, we have to find Is f(n)=O(g(n))?
ul P
To check f(n)=O(g(n)), it must satisfy the given condition:
f(n)<=c.g(n)
a h
2n+3 <= c.n R
First, we will replace f(n) by 2n+3 and g(n) by n.
23
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
The idea of using big o notation is to give an upper bound of a particular function, and eventually
it leads to give a worst-time complexity. It provides an assurance that a particular function does not
tio
behave suddenly as a quadratic or a cubic fashion, it just behaves in a linear manner in a worst-case.
Omega Notation ()
l i c a
It basically describes the best-case scenario which is opposite to the big o notation.
u b
It is the formal way to represent the lower bound of an algorithm’s running time. It measures the
ul P
best amount of time an algorithm can possibly take to complete or the best-case time complexity.
It determines what is the fastest time that an algorithm can run.
a h
If we required that an algorithm takes at least certain amount of time without using an upper
bound, we use big - notation i.e. the Greek letter “omega”. It is used to bound the growth of
R
running time for large input size.
If f(n) and g(n) are the two functions defined for positive integers, then f(n) = (g(n)) as f(n)
is Omega of g(n) or f(n) is on the order of g(n)) if there exists constants c and no such that:
f(n)>=c.g(n) for all n no and c>0
Let’s consider a simple example.
If f(n) = 2n+3, g(n) = n,
Is f(n)=(g(n))?
It must satisfy the condition:
f(n)>=c.g(n)
To check the above condition, we first replace f(n) by 2n+3 and g(n) by n.
2n+3>=c*n
Suppose c=1
2n+3>=n (This equation will be true for any value of n starting from 1).
Therefore, it is proved that g(n) is big omega of 2n+3 function.
24
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
As we can see in the above figure that g(n) function is the lower bound of the f(n) function when
a tio
the value of c is equal to 1. Therefore, this notation gives the fastest running time. But, we are not more
interested in finding the fastest running time, we are interested in calculating the worst-case scenarios
c
l i
because we want to check our algorithm for larger input that what is the worst time that it will take so that
we can take further decision in the further process.
b
Theta Notation ()
P u
a h ul
The theta notation mainly describes the average case scenarios.
It represents the realistic time complexity of an algorithm. Every time, an algorithm does not perform
R
worst or best, in real-world problems, algorithms mainly fluctuate between the worst-case and best-
case, and this gives us the average case of the algorithm.
Big theta is mainly used when the value of worst-case and the best-case is same.
It is the formal way to express both the upper bound and lower bound of an algorithm running
time.
Let f(n) and g(n) be the functions of n where n is the steps required to execute the program then:
f(n)= g(n)
c1.g(n)<=f(n)<=c2.g(n)
where the function is bounded by two limits, i.e., upper and lower limit, and f(n) comes in between.
The condition f(n)= g(n) will be true if and only if c1.g(n) is less than or equal to f(n) and c2.g(n) is
greater than or equal to f(n). The graphical representation of theta notation is given below:
25
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
g(n)=n
As c1.g(n) should be less than f(n) so c1 has to be 1 whereas c2.g(n) should be greater than f(n) so
c1.g(n)<=f(n)<=c2.g(n)
l i c a
c2 is equal to 5. The c1.g(n) is the lower limit of the of the f(n) while c2.g(n) is the upper limit of the f(n).
u
Replace g(n) by n and f(n) by 2n+3
b
c1.n <=2n+3<=c2.n
if c1=1, c2=2, n=1
ul P
a
1*1 <=2*1+3 <=2*1
h
R
1<= 5 <= 2 // for n=1, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
If n=2
1*2<=2*2+3<=2*2
2<=7<=4 // for n=2, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
Therefore, we can say that for any value of n, it satisfies the condition c1.g(n)<=f(n) <=c2.g(n).
Hence, it is proved that f(n) is big theta of g(n). So, this is the average-case scenario which provides the
realistic time complexity.
1.2 STACKS
1.2.1 Concepts of Stacks and Queues, Stacks, Stack Abstract Data type
Q28. What is a Stack? List out the standard operations of Stack ?
26
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
to the topmost element of the stack. Whenever an element is added in the stack, it is added on the top of
the stack, and the element can be deleted only from the stack. In other words, a stack can be defined as
a container in which insertion and deletion can be done from the one end known as the top of the stack.
It is called as stack because it behaves like a real-world stack, piles of books, etc.
A Stack is an abstract data type with a pre-defined capacity, which means that it can store the
elements of a limited size.
It is a data structure that follows some order to insert and delete the elements, and that order can be
LIFO or FILO.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let’s assume that stack is empty. We have
taken the stack of size 5 as shown below in which we are pushing the elements one by one until the stack
becomes full.
n s
c a tio
b l i
P u
a h ul
R
Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it goes from
the top to the bottom when we were entering the new element in the stack. The stack gets filled up from
the bottom to the top.
When we perform the delete operation on the stack, there is only one way for entry and exit as the
other end is closed. It follows the LIFO pattern, which means that the value entered first will be removed
last. In the above case, the value 5 is entered first, so it will be removed only after the deletion of all the
other elements.
The following are some common operations implemented on the stack:
push(): When we insert an element in a stack then the operation is known as a push. If the stack is
full then the overflow condition occurs.
pop(): When we delete an element from the stack, the operation is known as a pop. If the stack is
empty means that no element exists in the stack, this state is known as an underflow state.
27
Rahul Publications
B.Sc. II YEAR III SEMESTER
tio
i.e., top=top+1, and the element will be placed at the new position of the top.
l i c a
The elements will be inserted until we reach the max size of the stack.
u b
ul P
a h
R
28
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
tio
Q30. Discuss in detail Stack ADT.
Ans :
li c a (July-21, Dec.-17)
The abstract datatype is special kind of datatype, whose behavior is defined by a set of values and
u b
set of operations. The keyword “Abstract” is used as we can use these datatypes, we can perform different
operations. But how those operations are working that is totally hidden from the user. The ADT is made
l P
of with primitive datatypes, but operation logics are hidden.
u
Here we will see the stack ADT. These are few operations or functions of the Stack ADT.
R ah
isFull(), This is used to check whether stack is full or not
isEmpry(), This is used to check whether stack is empty or not
push(x), This is used to push x into the stack
pop(), This is used to delete one element from top of the stack
peek(), This is used to get the top most element of the stack
size(), this function is used to get number of elements present into the stack
Example:
#include<iostream>
#include<stack>
usingnamespacestd;
main(){
stack<int>stk;
if(stk.empty()){
cout<<“Stack is empty”<<endl;
29
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
item is deleted from the stack. The top most element
of the stack is stored in an another variable and
tio
stk.pop(); then the top is decremented by 1. the operation
returns the deleted value that was stored in another
}
cout<< item <<“ “;
l i c a
variable as the result.
The underflow condition occurs when we try
}
u b
to delete an element from an already empty stack.
Output
Stack is empty
ul P Algorithm :
begin
if top = 0 then stack empty;
Size of the stack: 5
a h item := stack(top);
50 40 30 20 10
R
1.2.2 Representation of Stacks Using
sequential organizations(Arrays)
top = top - 1;
end;
Peek operation involves returning the element
Q31. Explain the representation of stack using which is present at the top of the stack without
deleting it. Underflow condition can occur if we try
arrays implementation.
to return the top element in an already empty stack.
Ans : (June-18, Imp.) Algorithm :
In array implementation, the stack is formed PEEK (STACK, TOP)
by using the array. All the operations regarding the Begin
stack are performed using arrays. Lets see how each
if top = -1 then stack empty
operation can be implemented on the stack using
array data structure. item = stack[top]
return item
Adding an element into the top of the stack is
End
referred to as push operation. Push operation
involves following two steps. Example:
#include<iostream>
1. Increment the variable Top so that it can now
refere to the next memory location. usingnamespacestd;
30
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
cout<<“Exit”<<endl;
tio
} break;
} }
void display(){
if(top>=0){
l i c a default:{
l
cout<<stack[i]<<“ “;
cout<<endl;
u Pu }
}
ah
}while(ch!=4);
}else
return0;
}
int main(){
R
cout<<“Stack is empty”;
}
Output
intch,val; 1) Push in stack
cout<<“1) Push in stack”<<endl;
2) Pop from stack
cout<<“2) Pop from stack”<<endl;
cout<<“3) Display stack”<<endl; 3) Display stack
cout<<“4) Exit”<<endl; 4) Exit
do{ Enter choice: 1
cout<<“Enter choice: “<<endl; Enter value to be pushed: 2
cin>>ch;
Enter choice: 1
switch(ch){
Enter value to be pushed: 6
case1:{
cout<<“Enter value to be Enter choice: 1
pushed:”<<endl; Enter value to be pushed: 8
cin>>val; Enter choice: 1
31
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
In linked list implementation of stack, the nodes are maintained non-contiguously in the memory.
Each node contains a pointer to its immediate successor node in the stack. Stack is said to be overflown if
the space left in the memory heap is not enough to create a node.
l i c a
u b
ul P
a h
R
The top most node in the stack always contains null in its address field. Lets discuss the way in
which, each operation is performed in linked list implementation of stack.
Adding a node to the stack is referred to as push operation. Pushing an element to a stack in
linked list implementation is different from that of an array implementation. In order to push an element
onto the stack, the following steps are involved.
32
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
c a tio
b l i
P u
a h ul
R
Deleting a node from the top of stack is referred to as pop operation. Deleting a node from the
linked list implementation of stack is different from that in the array implementation. In order to pop an
element from the stack, we need to follow the following steps :
1. Check for the underflow condition: The underflow condition occurs when we try to pop from
an already empty stack. The stack will be empty if the head pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the elements are popped only from one end,
therefore, the value stored in the head pointer must be deleted and the node must be freed. The
next node of the head node now becomes the head node.
Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in the
form of stack. For this purpose, we need to follow the following steps.
33
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
top=newnode; break;
} }
void pop(){
if(top==NULL)
l i c a case3:{
display();
cout<<“Stack Underflow”<<endl;
else{
u b break;
ul P
cout<<“The popped element is “<< top-
>data <<endl;
}
case4:{
}
top= top->next;
a h cout<<“Exit”<<endl;
break;
}
void display(){
structNode*ptr;
R }
default:{
cout<<“Invalid Choice”<<endl;
if(top==NULL) }
cout<<“stack is empty”;
}
else{
}while(ch!=4);
ptr= top;
return0;
cout<<“Stack elements are: “;
while(ptr!= NULL){ }
cout<<ptr->data <<“ “; Output
ptr=ptr->next; 1) Push in stack
}
} 2) Pop from stack
cout<<endl; 3) Display stack
}
4) Exit
int main(){
intch,val; Enter choice: 1
34
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
tio
Enter choice: 4
Exit
1.2.3 Multiple Stack
l i c a
program.
u b
Q33. What is multiple stack ? What is the use of Multiple stack ? Explain with an example
Ans :
ul P
a h
A single stack is sometime not sufficient to store large amount of data. To overcome this problem we
can use multiple stack. For this, we have used a single array having more than one stack. The array is
R
divided for multiple stacks.
Suppose, there is an array STACK[n] divided into two stack STACK A and STACK B, where
n = 10.
STACK A expands from the left to right, i.e. from 0th element.
STACK B expands from the right to left, i.e, from 10th element.
The combined size of both STACK A and STACK B never exceed 10.
35
Rahul Publications
B.Sc. II YEAR III SEMESTER
Example: inti;
#include<iostream> if(r.IsEmpty())
using namespace std; cout<<“\nRed stack is empty”;
#define MAX 5 else
class Stack {
{ cout<<“\nItems in the Red stack \n”;
public: for(i=r.top;i>=0;i—)
int a[MAX]; cout<<r.a[i]<<endl;
int top; }
Stack() if(g.IsEmpty())
{ cout<<“\nGreen stack is empty”;
top=-1; else
} {
intgetdata(); cout<<“\nItems in the Green stack \n”;
boolIsEmpty(); for(i=g.top;i>=0;i—)
boolIsFull(); cout<<g.a[i]<<endl;
n s
tio
void push(); }
void pop();
};
i a
if(b.IsEmpty())
c
cout<<“\nBlue stack is empty”;
l
int Stack::getdata()
{
u b
else
{
int data;
cout<<“\nEnter the Element “;
ul P cout<<“\nItems in the Blue stack \n”;
for(i=b.top;i>=0;i—)
cin>>data;
return data;
a h cout<<b.a[i]<<endl;
}
}
bool Stack::IsEmpty()
R }
void Stack::push()
{ {
if(top==-1) if(IsFull())
return 1; cout<<“\n stack is full”;
return 0; else
} {
bool Stack::IsFull() top++;
{ a[top]=getdata();
if(top==MAX) }
return 1; }
return 0; void Stack::pop()
} {
void display(Stack &r,Stack&g,Stack&b) if(IsEmpty())
{ cout<<“\nstack is empty”;
36
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n
Enter Your Choice 1s
tio
cout<<“\n 7:Show”; Enter the Element 20
cout<<“\n 8:Exit”;
cout<<“\n Enter Your Choice “;
1.
l i a
Main menu
c
Push red
cin>>ch;
b
2. Push green
Pu
switch(ch)
3. Push blue
{
case 1: red.push(); break;
ul 4.
5.
Pop red
Pop green
ah
case 2: green.push(); break;
6. Pop blue
case 3: blue.push(); break;
R
case 4: red.pop(); break;
case 5: green.pop(); break;
7.
8.
Show
Exit
Enter Your Choice 1
case 6: blue.pop(); break;
Enter the Element 30
case 7: display(red,green,blue); break;
Main menu
case 8: temp=1; break;
1. Push red
default: cout<<“\n wrong choice”;
2. Push green
}
3. Push blue
}while(ch!=8 && temp!=1);
4. Pop red
}
5. Pop green
Output
6. Pop blue
Main menu
7. Show
1. Push red
2. Push green 8. Exit
3. Push blue Enter Your Choice 2
4. Pop red Enter the Element 100
37
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
4. Pop red 100
5. Pop green Blue stack is empty
6.
7.
Pop blue
Show
l i c a
Main menu
8. Exit
u b
1.
2.
Push red
Push green
Enter Your Choice 7
Items in the Red stack
ul P 3.
4.
Push blue
Pop red
ah
30
5. Pop green
20
10
R
Items in the Green stack
6.
7.
8.
Pop blue
Show
Exit
200
Enter Your Choice 8
100
1.2.4 Applications of Stack, Expression
Blue stack is empty evaluation and conversion, polish
Main menu notation and Expression convertion
1. Push red Q34. List out the applications of Stack.
2. Push green
Ans :
3. Push blue
4. Pop red The following are the applications of the stack:
38
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
cout<<“Hello”; Backtracking
cout<<“Student”; Suppose we have to create a path to solve a
maze problem. If we are moving in a particular
}
path, and we realize that we come on the
As we know, each program has an wrong way. In order to come at the beginning
opening and closing braces; when the opening of the path to create a new path, we have to
braces come, we push the braces in a stack, and use the stack data structure.
when the closing braces appear, we pop the opening
Expression conversion
braces from the stack. Therefore, the net value
comes out to be zero. If any symbol is left in the Stack can also be used for expression
stack, it means that some syntax occurs in a conversion. This is one of the most important
program. applications of stack. The list of the expression
conversion is given below:
String reversal
Infix to prefix
Stack is also used for reversing a string. For
example, we want to reverse a “Student” Infix to postfix
string, so we can achieve this with the help of Prefix to infix
a stack.
First, we push all the characters of the string
Prefix to postfix
n s
tio
in a stack until we reach the null character. Postfix to infix
l i c a
Memory management
The stack manages the memory. The memory
the bottom of the stack.
ul P
It can also be used for performing UNDO/
REDO operations. For example, we have an
all the variables are assigned in a function call
stack memory. The memory size assigned to
a h
editor in which we write ‘a’, then ‘b’, and the program is known to the compiler. When
the function is created, all its variables are
R
then ‘c’; therefore, the text written in an editor
is abc. So, there are three states, a, ab, and
abc, which are stored in a stack. There would
be two stacks in which one stack shows UNDO
assigned in the stack memory. When the
function completed its execution, all the
variables assigned in the stack are released.
state, and the other shows REDO state.
Q35. Explain various types of notations used
If we want to perform UNDO operation, and to evaluate the expression using data
want to achieve ‘ab’ state, then we structures.
implement pop operation.
Ans : (July-21)
Recursion
The way to write arithmetic expression is
The recursion means that the function is calling known as a notation. An arithmetic expression can
itself again. To maintain the previous states, be written in three different but equivalent notations,
the compiler creates a system stack in which i.e., without changing the essence or output of an
all the previous records of the function are expression. These notations are “
maintained.
• Infix Notation
DFS(Depth First Search)
• Prefix (Polish) Notation
This search is implemented on a Graph, and
Graph uses the stack data structure. • Postfix (Reverse-Polish) Notation
39
Rahul Publications
B.Sc. II YEAR III SEMESTER
These notations are named as how they use operator in expression. We shall learn the same here in
this chapter.
Infix Notation
We write expression in infix notation, e.g. a – b + c, where operators are used in-between
operands. It is easy for us humans to read, write, and speak in infix notation but the same does not go well
with computing devices. An algorithm to process infix notation could be difficult and costly in terms of
time and space consumption.
Prefix Notation
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish
Notation.
Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style, the operator
s
is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is
n
tio
equivalent to its infix notation a + b.
l i c a
The following table briefly tries to show the difference in all three notations -
Prefix Notation Postfix Notation
1 a+b
u +ab
b ab+
2
3
(a + b) * c
ul
a * (b + c)
P *+abc
*a+bc
ab+c*
abc+*
4
5
R ah
a/b+c/d
(a + b) * (c + d)
+/ab/cd
*+ab+cd
ab/cd/+
ab+cd+*
6 ((a + b) * c) – d -*+abcd ab+c*d-
a + b*c a + (b*c)
40
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
As multiplication operation has precedence over addition, b * c will be evaluated first. A table of
operator precedence is provided later.
Associativity
Associativity describes the rule where operators with the same precedence appear in an expression.
For example, in expression a + b “ c, both + and – have the same precedence, then which part of the
expression will be evaluated first, is determined by associativity of those operators. Here, both + and “ are
left associative, so the expression will be evaluated as (a + b) – c.
Precedence and associativity determines the order of evaluation of an expression. Following is an operator
precedence and associativity table (highest to lowest) -
n
tio
3 Addition (+) & Subtraction (–) Lowest Left Associative
u b
In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over
Ans :
a h
R
Polish notation is a notation form for expressing arithmetic, logic and algebraic equations. Its most
basic distinguishing feature is that operators are placed on the left of their operands. If the operator has a
defined fixed number of operands, the syntax does not require brackets or parenthesis to lessen ambiguity.
Polish notation is also known as prefix notation, prefix Polish notation, normal Polish notation, Warsaw
notation and Lukasiewicz notation.
Ans :
In reverse polish notation, the operator is placed after the operands like xy+, and it is also called
Postfix notation.
In both polish and reverse polish notation we don’t require the parentheses because all the operators
are arranged in their precedence associativity rule.
^ > * = / > - = +
41
Rahul Publications
B.Sc. II YEAR III SEMESTER
c
Main Feature: the binary operator is between the two operands.
a tio
Question
b l i
P u
what if we do not put all the parentheses? Then there are ambiguities on how to interpret an
expression: is 1+2*3 the same as (1+2)*3 or the same as 1+(2*3)? The precedence of operators solves
ul
this problem.
Prefix form
a h
Main Feature:the operator preceeds the two operands.
R
Recursive definition of fully parenthesized version:
prefix-expression:=(operand prefix-expression prefix-expression)
prefix-expression:= atom
Recursive definition of classic version, without parentheses (we do not need them, because there is
no longer any ambiguity on how to match the operands to the operators):
prefix-expression:= operand prefix-expression prefix-expression
prefix-expression:= atom
Examples
(* 3 7) or simply * 3 7
(* ( + 1 3) 2) or simply * + 1 3 2
( * ( + 1 3) ( - 2 3)) or simply * + 1 3 - 2 3
Postfix form
Main Feature: the operator is after the two operands. Recursive definition
postfix-expression:=(operand postfix-expression postfix-expression)
42
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
postfix-expression:= atom
Recursive definition of classic version, without parentheses (we do not need them, because there is
no longer any ambiguity on how to match the operands to the operators):
postfix-expression:= atom
Examples
(3 7 *) or simply 3 7 *
((1 3 + ) 2 *) or simply 1 3 + 2 *
((1 3 +) ( 2 3 -) * ) or simply 1 3 + 2 3 - *
Associativity
Associativity describes the rule where operators with the same precedence appear in an expression.
n s
For example, in the expression a + b – c, both + and – have the same precedence, then which part of the
expression will be evaluated first, is determined by associativity of those operators. Here, both + and “ are
tio
left associative, so the expression will be evaluated as (a + b) – c.
c
Sr.No. Operator
u b Precedence Associativity
2
Exponentiation ^
ul P
Multiplication (*) & Division (/)
Highest
Second Highest
Right Associative
Left Associative
3
a h
Addition (+) & Subtraction (–) Lowest Left Associative
R
The above table shows the default behavior of operators. At any point of time in expression evaluation,
the order can be altered by using parenthesis. For example-
In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over
addition. We here use parenthesis for a + b to be evaluated first, like (a + b)*c.
• Infix A + B, 3*x – y
=> A + [B*C]
=> A+[BC*]
43
Rahul Publications
B.Sc. II YEAR III SEMESTER
=> A [BC*] +
=> ABC * +
Converting to Infix to Prefix
A+B*C
=> A + [B*C]
=> A+[*BC]
=> + A [*BC]
=> + A * BC
Q40. Explain infix notation in detail. What are the problems associated with infix notation?
Ans :
When the operator is written in between the operands, then it is known as infix notation. Operand
does not have to be always a constant or a variable; it can also be an expression itself.
For example,
n s
tio
(p + q) * (r + s)
In the above expression, both the expressions of the multiplication operator are the operands,
i.e., (p + q), and (r + s) are the operands.
l i c a
u b
In the above expression, there are three operators. The operands for the first plus operator are p
and q, the operands for the second plus operator are r and s. While performing the operations on the
ul P
expression, we need to follow some set of rules to evaluate the result. In the above expression, addition
operation would be performed on the two expressions, i.e., p+q and r+s, and then the multiplication
operation would be performed.
a h
Syntax of infix notation is given below:
R
<operand><operator><operand>
If there is only one operator in the expression, we do not require applying any rule. For example,
5 + 2; in this expression, addition operation can be performed between the two operands (5 and 2), and
the result of the operation would be 7.
If there are multiple operators in the expression, then some rule needs to be followed to evaluate
the expression.
If the expression is:
4+6*2
If the plus operator is evaluated first, then the expression would look like:
10 * 2 = 20
If the multiplication operator is evaluated first, then the expression would look like:
4 + 12 = 16
The above problem can be resolved by following the operator precedence rules. In the algebraic
expression, the order of the operator precedence is given in the below table:
44
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Operators Symbols
Parenthesis , ,
Exponents ^
Multiplication and Division *, /
Addition and Subtraction ,
The first preference is given to the parenthesis; then next preference is given to the exponents. In
the case of multiple exponent operators, then the operation will be applied from right to left.
For example:
2^2^3 = 2 ^ 8
= 256
After exponent, multiplication, and division operators are evaluated. If both the operators are
present in the expression, then the operation will be applied from left to right.
n s
The next preference is given to addition and subtraction. If both the operators are available in the
expression, then we go from left to right.
c a tio
The operators that have the same precedence termed as operator associativity. If we go from left to
l i
right, then it is known as left-associative. If we go from right to left, then it is known as right-associative.
b
Problem with infix notation
P u
ul
To evaluate the infix expression, we should know about the operator precedence rules, and if the
operators have the same precedence, then we should follow the associativity rules. The use of parenthesis
a h
is very important in infix notation to control the order in which the operation to be performed. Parenthesis
improves the readability of the expression. An infix expression is the most common way of writing
R
expression, but it is not easy to parse and evaluate the infix expression without ambiguity. So, mathematicians
and logicians studied this problem and discovered two other ways of writing expressions which are prefix
and postfix. Both expressions do not require any parenthesis and can be parsed without ambiguity. It
does not require operator precedence and associativity rules.
Q41. Discuss in detail postfix notaion. Write the algorithm to evaluate postfix notation.
Ans :
Postfix Expression
The postfix expression is an expression in which the operator is written after the operands. For
example, the postfix expression of infix notation ( 2+3) can be written as 23+.
In postfix expression, operations are performed in the order in which they have written from left to
right.
45
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
= 14
Evaluation of postfix expression using stack.
b l i
1.
P u
Scan the expression from left to right.
2.
3.
a h ul
If we encounter any operand in the expression, then we push the operand in the stack.
When we encounter any operator in the expression, then we pop the corresponding operands
4. R
from the stack.
When we finish with the scanning of the expression, the final value remains in the stack.
Let’s understand the evaluation of postfix expression using stack.
Example 1: Postfix expression: 2 3 4 * +
Input Stack
234*+ empty Push 2
34*+ 2 Push 3
4*+ 32 Push 4
*+ 432 Pop 4 and 3, and perform 4*3 = 12. Push 12 into the
stack.
+ 12 2 Pop 12 and 2 from the stack, and perform 12 + 2 = 14.
Push 14 into the stack.
46
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
1. Read a character
2. If the character is a digit, convert the character into int and push the integer into the stack.
• Pop the elements from the stack twice obtaining two operands.
Ans :
Algorithm to Convert Infix to Postfix Expression Using Stack
n s
tio
1. Initialize the Stack.
2.
c
Scan the operator from left to right in the infix expression.
l i a
3.
b
If the leftmost character is an operand, set it as the current output to the Postfix string.
u
4.
P
And if the scanned character is the operator and the Stack is empty or contains the ‘(‘, ‘)’ symbol,
ul
push the operator into the Stack.
5.
h
If the scanned operator has higher precedence than the existing precedence operator in the
a
Stack or if the Stack is empty, put it on the Stack.
6. R
If the scanned operator has lower precedence than the existing operator in the Stack, pop all the
Stack operators. After that, push the scanned operator into the Stack.
7. If the scanned character is a left bracket ‘(‘, push it into the Stack.
8. If we encountered right bracket ‘)’, pop the Stack and print all output string character until ‘(‘ is
encountered and discard both the bracket.
11. Pop and output all characters, including the operator, from the Stack until it is not empty.
12. Let’s translate an infix expression into postfix expression in the stack:
13. Here, we have infix expression (( A * (B + D)/E) - F * (G + H / K))) to convert into its equivalent
postfix expression:
47
Rahul Publications
B.Sc. II YEAR III SEMESTER
1 ( (
2 ( ((
3 A (( A
4 * ((* A
5 ( ((*( A
6 B ((*( AB
7 + ((*(+ AB
8 D ((*(+ ABD
9 ) ((* ABD+
10 / ((*/ ABD+
n s
11 E ((*/
c a tio
ABD+E
12 )
b
(
l i ABD+E/*
13 -
P u (- ABD+E/*
ul
14 ( (-( ABD+E/*
15
a hF (-( ABD+E/*F
16
17
R *
(
(-(*
(-(*(
ABD+E/*F
ABD+E/*F
18 G (-(*( ABD+E/*FG
19 + (-(*(+ ABD+E/*FG
20 H (-(*(+ ABD+E/*FGH
21 / (-(*(+/ ABD+E/*FGH
22 K (-(*(+/ ABD+E/*FGHK
23 ) (-(* ABD+E/*FGHK/+
24 ) (- ABD+E/*FGHK/+*
25 ) ABD+E/*FGHK/+*-
48
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Q43. Convert the following given expression from infix to postfix A+(B*C+D)/E
Ans :
Input Postfix Action
Token Stack Expression
A A Add A into expression string
+ + A Push ‘+’ into stack
( +( A Push ( into stack
B +( AB Add B into expression string
* +(* AB Push ‘*’ into stack
C +(* ABC ‘+’ operator has less precedence than
‘*’, so pop * and add to expression
string
n s
tio
D +(+ ABC*D Add D into expression string
) + ABC*D+ ) has come so pop + and add it to
l i c a
expression string.
/ +/ ABC*D+
b / has higher precedence than + so
E +/
ul Pu
ABC*D+E/+
push / into stack
Add E into expression string and pop
ah
all operators one by one from stack
49
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
string infix_expression, postfix_expression;
int ch;
do
{
cout << ” Enter an infix expression: ”;
cin >> infix_expression;
postfix_expression = convert(infix_expression);
cout << ”\n Your Infix expression is: ” << infix_expression;
cout << ”\n Postfix expression is: ” << postfix_expression;
cout << ”\n \t Do you want to enter infix expression (1/ 0)?”;
cin >> ch;
//cin.ignore();
} while(ch == 1);
return 0;
}
n s
tio
// define the IsOperator() function to validate whether any symbol is operator.
/* If the symbol is operator, it returns true, otherwise false. */
bool IsOperator(char c)
{
l i c a
u b
if(c == ’+’ || c == ’-’ || c == ’*’ || c == ’/’ || c == ’^’ )
return true;
return false;
ul P
}
a h
// IsOperand() function is used to validate whether the character is operand.
{ R
bool IsOperand(char c)
50
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
tio
{
if (op1 == ’^’ )
return false;
return true;
l i c a
}
u b
return (p1>p2 ? true : false);
}
ul P
a h
/* string convert() function is used to convert the infix
expression to the postfix expression of the Stack */
{
stack <char> S;
R
string convert(string infix)
51
Rahul Publications
B.Sc. II YEAR III SEMESTER
else if(IsOperator(ch))
{
while(!S.empty() && eqlOrhigher(S.top(), ch))
{
postfix += S.top();
S.pop();
}
S.push(ch);
}
else if(ch == ’)’)
{
while(!S.empty() && S.top() != ’(‘)
{
postfix += S.top();
S.pop();
n s
tio
}
S.pop();
}
l i c a
}
u b
return postfix;
}
ul P
Output:
a h
R
52
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Ans :
Infix to Prefix Conversion Algorithm
Iterate the given expression from left to right, one character at a time
Step 1: First reverse the given expression
Step 2: If the scanned character is an operand, put it into prefix expression.
Step 3: If the scanned character is an operator and operator’s stack is empty, push operator into operators’
stack.
Step 4: If the operator’s stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of operator’s stack,
push this operator into operator ‘s stack.
If the precedence of scanned operator is less than the top most operator of operator’s stack, pop
the operators from operator’s stack untill we find a low precedence operator than the scanned character.
n s
If the precedence of scanned operator is equal then check the associativity of the operator. If
associativity left to right then simply put into stack. If associativity right to left then pop the operators from
tio
stack until we find a low precedence operator.
l i a
If the scanned character is opening round bracket ( ‘(‘ ), push it into operator’s stack.
c
If the scanned character is closing round bracket ( ‘)’ ), pop out operators from operator’s stack
until we find an opening bracket (‘(‘ ).
u
Repeat Step 2,3 and 4 till expression has character b
ul P
Step 5: Now pop out all the remaining operators from the operator’s stack and push into postfix expression.
Step 6: Exit
a h
Infix to Prefix conversion example
R
Infix Expression: (A+B)+C-(D-E)^F
First reverse the given infix expression
After Reversing: F^)E-D(-C+)B+A(
53
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
#include<algorithm>
P u
#include<locale>//for function isalnum()
ul
usingnamespacestd;
intpreced(charch){
a h
if(ch==’+’||ch==’-’){
R
return1; //Precedence of + or - is 1
}elseif(ch==’*’||ch==’/’){
return2; //Precedence of * or / is 2
}elseif(ch==’^’){
return3; //Precedence of ^ is 3
}else{
return0;
}
}
stringinToPost(string infix){
stack<char>stk;
stk.push(‘#’); //add some extra character to avoid underflow
string postfix =””; //initially the postfix string is empty
string::iterator it;
for(it =infix.begin(); it!=infix.end(); it++){
if(isalnum(char(*it)))
54
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
tio
postfix+=stk.top(); //store and pop until higher precedence is found
stk.pop();
}
stk.push(*it);
l i c a
}
u b
}
}
ul P
ah
while(stk.top()!=’#’){
postfix+=stk.top(); //store and pop until stack is not empty
}
stk.pop();
return postfix;
R
}
stringinToPre(string infix){
string prefix;
reverse(infix.begin(),infix.end());
/ /reverse the infix expression
string::iterator it;
for(it =infix.begin(); it !=infix.end(); it++){ //reverse the parenthesis after reverse
if(*it ==’(‘)
*it =’)’;
elseif(*it ==’)’)
*it =’(‘;
}
prefix=inToPost(infix);
55
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
he steps required for Postfix to Infix Conversion are as follows:
n s
tio
1. Scan the postfix expression from left to right.
2. Initialize an empty string stack.
3. If the scanned character is operand, push it into stack.
l i c a
4.
b
Else if the scanned character is operator, pop two strings from stack, namely, temp1 and temp2,
u
and push: (temp2 operator temp1) into stack.
5.
6.
ul P
Repeat steps from 3 to 4 until all the characters from the string are scanned.
In the end, only one valid infix string will be present in the stack, pop it and return it.
Example:
a h
R
abc * de / ((a ((b * c) / (d e))))
SYMBOL STACK
a a
b a| b
c a|b|c
* a|(b * c)
d a |(b * c)|d
e a|(b * c)|d|e
a |(b * c)|(d e)
/ a|((b * c) / (d e))
(a ((b * c) / (d e)))
56
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Program : };
/* Program for Postfix to Infix Conversion */ int main(intargc, char** argv)
#include <iostream> {
#include<string> inti,j=0;
#define sizes 100 stackst;
using namespace std; stringpostfix,infix;
class stack cout<<“Enter postfix expression:\n”;
{ cin>>postfix;
int top; {
if(postfix[i]==’+’ || postfix[i]==’-’
public:
|| postfix[i]==’*’ || postfix[i]==’/’
stack()
|| postfix[i]==’^’)
{
top=-1;
{
n s
tio
string temp,op1,op2;
}
a
op2=st.pop();
void push(string str)
{
if(top==sizes-1)
b li c op1=st.pop();
temp=’(‘+op1+postfix[i]+op2+’)’;
{
P u st.push(temp);
u
return;l
cout<<“stack overflow!!\n”; }
ah
else
}
{
}
R
top++;
item[top]=str;
string flag;
flag=flag+postfix[i];
57
Rahul Publications
B.Sc. II YEAR III SEMESTER
Q48. Explain the process of converting an expression from postfix to prefix with an example.
Ans :
The Steps required to convert Postfix to Prefix Expression are as follows:
1. Scan the string from left to right.
2. Initialize an empty string stack.
3. If the scanned character is operand, push it into stack.
4. Else if the scanned character is operator, pop two strings from stack, namely, temp1 and temp2,
and push ”operator temp1 temp2" into stack.
5. Repeat steps from 3 to 4 until all the characters of the strings are scanned.
6. In the last only a single valid prefix string will be in the stack, pop it and return it.
Example:
abc*de-/+=+a/*bc-de
SYMBOL
a
STACK
a
n s
b
c
a |b
a |b|c
c a tio
*
d
a|*bc
b l
a |*bc |d i
Pu
e a |*bc |d|e
ul
/
a |*bc | de
a| / * bc de
Program:
R ah a / *bc de
58
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
{
top=-1;
}
void push(string str)
{
if(top==sizes-1)
{
cout<<“stack overflow!!”;
return;
}
top++;
item[top]=str;
}
string pop()
n s
{
string temp;
c a tio
if(top==-1)
b l i
{
P u
ul
cout<<“stack underflow!!”;
return “abc”;
}
a h
R
temp= item[top];
top - -;
return temp;
}
};
int main(intargc, char** argv) {
stack st;
string postfix;
inti;
cout<<“Enter the valid postfix string:\n”;
cin>>postfix;
for(i=0;i<postfix.size();i++)
{
59
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
}
l i c a
u
cout<<“The equivalent prefix expression:\n”<<st.pop();b
return 0;
ul P
}
OUTPUT
a h
R
Enter valid postfix expression:
abc*de-/+
The equivalent prefix expression:
+a/*bc-de
Q49. Explain the process of converting prefix to infix with an example.
Ans :
The Steps to convert Prefix to Infix Using Stack Expression are as follows:
1. Scan the Prefix Expression form right to left.
2. Initialize the string stack.
3. If the scanned character is operand, push it into stack.
4. Else if the scanned character is operator, pop two strings from the stack namely, temp1 and temp2,
then push (temp1 operator temp2) into stack.
60
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
SYMBOL STACK
e e
d e|d
(d e)
c (d e)|c
b (d e)|c |b
* (d e)|(b * c)
/ ((b * c) / (d e))
a ((b * c) / (d e))|a
n s
tio
(a ((b * c) / (d e)))
61
Rahul Publications
B.Sc. II YEAR III SEMESTER
return;
}
top++;
item[top]=st;
}
string pop()
{
inti;
string temp;
if(top==-1)
{
cout<<“stack underflow!!\n”;
return “abc”;
}
temp = item[top];
top—;
n s
tio
return temp;
}
};
int main(intargc, char** argv)
l i c a
{
u b
inti;
stack st;
ul P
a h
string prefix;
cout<<“Enter valid prefix string: “;
R
cin>>prefix;
for(i=prefix.size()-1;i>=0;i—)
{
if(prefix[i]==’+’ || prefix[i]==’-’ || prefix[i]==’*’ || prefix[i]==’/’ || prefix[i]==’^’)
{
string op1,op2,temp;
op1=st.pop();
op2=st.pop();
temp=’(‘+op1+prefix[i]+op2+’)’;
st.push(temp);
}
else
{
string flag;
62
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
flag=flag+prefix[i];
st.push(flag);
}
}
cout<<“The resultant infix string is: “<<st.pop();
return 0;}
OUTPUT
Enter valid Prefix String: +a/*bc-de
The resultant infix string: (a+((b*c)/(d-e)))
Q50. Explain the process of converting prefix to postfix expression.
Ans :
The steps required for Prefix to Postfix Conversion are as follows:
1. Scan the prefix string in reverse order.
n s
2. Initialize an empty string stack.
c a tio
3.
4.
If the scanned character is operand, push it into stack.
b l i
Else if, the scanned character is operator, pop two strings from the stack, namely, temp1 and
u
temp2, then push temp1 temp2 operator into stack.
P
ul
5. Repeat steps from 3 to 4 until all the characters of the strings are scanned.
6.
h
Lastly, single postfix string will be left in stack, pop it and return it.
Example:
a
R
a / *bc de abc * de /
NOTE : Scan the prefix string in reverse order.
SYMBOL STACK
e e
d e|d
de
c de |c
b de |c|b
* de |bc *
/ bc * de /
a bc * de / |a
abc * de /
63
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
if(top==sizes-1)
{
cout<<“stack overflow!!”;
return;
l i c a
}
u b
top++;
item[top]=str;
ul P
}
a h
string pop()
{
R if(top==-1)
{
cout<<“stack underflow!!”;
return “abc”;
}
string temp;
temp=item[top];
top - -;
return temp;
}
};
int main(intargc, char** argv)
{
inti;
string prefix;
64
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
stack st;
cout<<“Enter valid prefix expression: “;
cin>>prefix;
for(i=prefix.size()-1;i>=0;i--)
{
if(prefix[i]==’+’ || prefix[i]==’-’ || prefix[i]==’*’ || prefix[i]==’/’
|| prefix[i]==’^’)
{
string op1,op2,temp;
op1=st.pop();
op2=st.pop();
temp=op1+op2+prefix[i];
st.push(temp);
}
else
{
n s
string flag;
flag=flag+prefix[i];
c a tio
}
st.push(flag);
b l i
}
P u
ul
cout<<“The equivalent postfix expression: “<<st.pop();
}
return 0;
a h
OUTPUT
R
Enter valid prefix expression: +a/*bc-de
The equivalent Postfix expression: abc*de-/+
1.2.5 Processing of Function calls
Q51. What is the use of function calls in stack implementation?
Ans : (July-19, Imp.)
Some computer programming languages allow a module or function to call itself. This technique is
known as recursion. In recursion, a function either calls itself directly or calls a function that in turn
calls the original function . The function is called recursive function.
Example:
int function1(int value1){
if(value1 <1)
return;
function2(value1 -1);
65
Rahul Publications
B.Sc. II YEAR III SEMESTER
cout<<“%d “,value1;
}
int function2(int value2){
function1(value2);
}
Properties
A recursive function can go infinite like a loop. To avoid infinite running of recursive function, there
are two properties that a recursive function must have -
Base criteria d There must be at least one base criteria or condition, such that, when this condition
is met the function stops calling itself recursively.
Progressive approach d The recursive calls should progress in such a way that each time a recursive
call is made it comes closer to the base criteria.
Implementation
n s
Many programming languages implement recursion by means of stacks. Generally, whenever a
function (caller) calls another function (callee) or itself as callee, the caller function transfers execution
tio
control to the callee. This transfer process may also involve some data to be passed from the caller to the
callee.
i c a
This implies, the caller function has to suspend its execution temporarily and resume later when the
l
u b
execution control returns from the callee function. Here, the caller function needs to start exactly from the
point of execution where it puts itself on hold. It also needs the exact same data values it was working on.
P
For this purpose, an activation record (or stack frame) is created for the caller function.
ul
a h
R
This activation record keeps the information about local variables, formal parameters, return address
and all information passed to the caller function.
66
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
tio
is considered that space complexity of recursive characters.
function may go higher than that of a function with
iteration.
As an example, consider the following
3.
l i a
Traverse the string and push each and every
c
character into the stack one by one.
program:
u b
4. Traverse again and start popping the
characters out and concatenate them together
voidbar() {
}
ul P 5.
into a string.
Print the reversed string.
ah
voidfoo() { Q53. Write a C++ program to reverse a string
bar();
}
intmain() {
R Ans :
using stack.
#include <bits/stdc++.h>
(July-21, July-19)
usingnamespacestd;
foo();
class Stack{
}
public:
When the program is run, the main() function int top;
is called, so an activation record is created and
unsigned capacity;
added to the top of the stack. Then
main() calls foo(), which places an activation char* array;
record for foo() on the top of the stack. };
Then bar() is called, so its activation record is put Stack* createStack(unsigned capacity){
on the stack. When bar() returns, its activation Stack* stack = newStack();
record is removed from the stack. Then stack->capacity = capacity;
foo() completes, removing its activation record.
stack->top = -1;
Finally, the activation record for main() is destroyed
when the function returns. Following figure shows stack->array = newchar[(stack->capacity *
the state of the stack after each call and return. sizeof(char))];
67
Rahul Publications
B.Sc. II YEAR III SEMESTER
l i a
Push(D)
c
TOP is D
voidreverse(char s[]){
b
Pu
STEP5 :
int n = strlen(s);
Push(E)
ul
Stack* stack = createStack(n);
TOP is E
ah
inti;
STEP6 :
for(i = 0; i< n; i++){
R
Push(F)
push(stack, s[i]);
TOP is F
}
Now take other stack. Remove the elements
for(i = 0; i< n; i++){ of the first stack and insert into the second stack.
s[i] = pop(stack); Stack 1 Stack2
} POP(F) Push(F)
} POP(E) Push(E)
intmain(){ POP(D) Push(D)
char s[] = “TutorialCup”; POP(C) Push(C)
reverse(s); POP(B) Push(B)
cout<<s; POP(A) Push(A)
return 0; Now the elements present in stack are displayed by
} using display()
Output Output:
puClairotuT “ FEDCBA”
68
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
1.2.7 Recursion
Q55. What is recursion ?
Ans :
The process in which a function calls itself is known as recursion and the corresponding function is
called the recursive function. The popular example to understand the recursion is factorial function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil
discuss what is base condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
Factorial function: f(n) = n*f(n–1)
Lets say we want to find out the factorial of 5 which means n = 5
f(5)=5*f(5 – 1)=5*f(4)
5*4*f(4–1)=20*f(3)
n s
tio
20*3*f(3 –1)=60*f(2)
l i
c a
b60*2*f(2–1)=120*f(1)
Pu
ul 120*1*f(1–1) = 120*f(0)
ah
120*1=120
R
Q56. Write a C++ Program to find factorial of a given number using recursion.
Ans :
#include<iostream>
usingnamespacestd;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
if(n <=1)
return1;
else
69
Rahul Publications
B.Sc. II YEAR III SEMESTER
return n*f(n-1);
}
int main(){
intnum;
cout<<“Enter a number: “;
cin>>num;
cout<<“Factorial of entered number: “<<f(num);
return0;
}
Output:
Enter a number:5
Factorial of entered number:120
Q57. List out advantages and disadvantages of recursion.
Ans :
n s
tio
Advantages of Recursion
It requires few variables which make program clean.
It shorten the complex and nested code.
l i c a
Disadvantages of Recursion
u
It is hard to debug recursive function. b
ul P
It is tough to understand the logic of a recursive function.
a h
It can cause infinite loop or unexpected results if not written correctly.
Recursive program has greater memory space requirements than iterative program.
R
Recursive programs are slower than non recursive programs.
70
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
ul P
Sorting: We can sort the elements of a data
structure either in an ascending or descending
Ans :
characteristics of an algorithm ?
order.
R
Insertion: We can also insert the new
element in a data structure.
Updation: We can also update the element,
problem-solving operations especially by a
computer. The formal definition of an algorithm is
that it contains the finite set of instructions which
i.e., we can replace the element with another
are being carried in a specific order to perform the
element.
specific task. It is not the complete program or code;
Deletion: We can also perform the delete it is just a solution (logic) of a problem, which can
operation to remove the element from the be represented either as an informal description
data structure.
using a Flowchart or Pseudo code.
2. List and explain advantages of data
The following are the characteristics of an
structures ? algorithm:
Ans : Input
Efficiency An algorithm has some input values. We can
Efficiency of a program depends upon the pass 0 or some input value to an algorithm.
choice of data structures. For example: suppose, Output
we have some data and we need to perform the We will get 1 or more output at the end of an
search for a perticular record. In that case, if we algorithm.
71
Rahul Publications
B.Sc. II YEAR III SEMESTER
Unambiguity Independent
An algorithm should be unambiguous which An algorithm should have step-by-step
means that the instructions in an algorithm directions, which should be independent of
should be clear and simple. any programming code.
tio
be implemented in any of the languages with Posterior Analysis
4.
the same output.
List out the basic characteristics of an
l i a
Here, posterior analysis is a practical analysis
c
of an algorithm. The practical analysis is
Ans :
algorithm.
Characteristics of an Algorithm
a h
Algorithm should be clear and unambiguous.
measured in two factors:
R
Each of its steps (or phases), and their inputs/
outputs should be clear and must lead to only
one meaning.
Time complexity
The time complexity of an algorithm is the
amount of time required to complete the
Input execution. The time complexity of an
algorithm is denoted by the big O notation.
An algorithm should have 0 or more well- Here, big O notation is the asymptotic
defined inputs. notation to represent the time complexity.
Output The time complexity is mainly calculated by
counting the number of steps to finish the
An algorithm should have 1 or more well-
execution. Let’s understand the time
defined outputs, and should match the
complexity through an example.
desired output.
sum=0;
Finiteness
// Suppose we have to calculate
Algorithms must terminate after a finite
number of steps. the sum of n numbers.
72
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
The extra space required by the algorithm, excluding the input size, is known as an auxiliary space.
tio
The space complexity considers both the spaces, i.e., auxiliary space, and space used by the input.
So,
Space complexity = Auxiliary space + Input size.
l i c a
6.
Ans : b
What are the differences between Pseudocode and Algorithms.
u
S. NO
ul
Pseudocode P Algorithm
1.
h
It is the method used for writing
a
It is another method of describing the
R
the computer program in easy ad
readable format or in the English
language to make it the user or
computer program in a readable ad under
standable with the sequence of steps written
to follow while writing the code.
developer easier to understand the
logic for further problem resolution.
2. It is said to be the representation of It is said to be the sequence of steps of
the algorithm as it is simpler to read explanation for the code with logical
and understand than the algorithm. steps that makes it easier but a bit difficult
to understand than pseudocode.
3. It is one of the simpler methods or It is one of the systematic and logical methods
versions for writing code in any or versions for writing code in any progra-
programming language. mming language.
73
Rahul Publications
B.Sc. II YEAR III SEMESTER
n
tio
because it is written in easy under constructing as it sometimes involves code
a
standing simpler for debugging. snippets in it and hence it is a bit difficult
l
Algorithms can be used in any complex
P u
complicated programming languages programming language as it uses simple
ul
as algorithms because it is widely used logical code snippets sometimes which is
when the combination of programming more than natural language as used
a h
and simple natural languages is required in Pseudocode constructions.
9.
R
for constructing the pseudocode.
The pseudocode also uses few specific
words or phrases or special symbols
The algorithm is written using some
specific criteria such as it includes input
to differentiate it from the algorithm, statement, output statement, also includes
though pseudocodes can be considered with effectiveness and efficiency of the
as a method of writing algorithms. It algorithm code written for a particular program,
includes a forward slash for beginning clear statements which are free from
comments, uses flower braces for in- ambiguity, also includes certain or proper
cluding logical blocks, italso uses some conditions to be displayed for correctly
operators to specify the logic of the code. terminating after few steps when required
in the code, and sometimes small logical
codes can also be written to specify some
logic directly.
10. Pseudocode cannot be considered Algorithms can be considered as
algorithms. pseudocode.
74
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n s
c a tio
8.
Ans :
What are the differences between algorithm and flow chart.
b l i
Flowchart
ul
Block by block information Pu Algorithm
Step by step instruction representing the
ah
diagram representing the data flow. process of any solution.
R
It is a pictorial representation of a process. It is a stepwise analysis of the work to be done.
The solution is shown in a graphical format. The solution is shown in a non-computer
language like English.
Easy to understand as compared to the It is somewhat difficult to understand.
algorithm.
Easy to show branching and looping. Difficult to show branching and looping
Flowchart for a big problem is impractical The algorithm can be written for any problem
Difficult to debug errors. Easy to debug errors.
It is easy to make a flowchart. It is difficult to write an algorithm as compared
to a flowchart.
9. What is time complexity?
Ans :
Time complexity of an algorithm signifies the total time required by the program to run till its
completion.
75
Rahul Publications
B.Sc. II YEAR III SEMESTER
The time complexity of algorithms is most This notation provides an upper bound on a
commonly expressed using the big O notation. It’s function which ensures that the function
an asymptotic notation to represent the time never grows faster than the upper bound.
complexity.Time Complexity is most commonly So, it gives the least upper bound on a
estimated by counting the number of elementary function so that the function never grows
steps performed by any algorithm to finish faster than this upper bound.
execution.
It is the formal way to express the upper
10. What is mean by space complexity. boundary of an algorithm running time. It measures
the worst case of time complexity or the algorithm’s
Ans : longest amount of time to complete its operation. It
Space complexity is an amount of memory is represented as shown below:
used by the algorithm (including the input values
of the algorithm), to execute it completely and
produce the result.
We know that to execute an algorithm it must
be loaded in the main memory. The memory can
be used in different forms:
Variables (This includes the constant values
and temporary values)
n s
Program Instruction
c a tio
Execution
Auxiliary Space
b l i
u
Auxiliary space is extra space or temporary
P
space used by the algorithms during its execution.
12. Define a stack.
ul
Ans :
Memory Usage during program execution
h
A Stack is a linear data structure that follows
a
Instruction Space is used to save compiled
R
instruction in the memory.
Environmental Stack is used to storing the
the LIFO (Last-In-First-Out) principle. Stack has
one end, whereas the Queue has two ends (front
and rear). It contains only one pointer top
pointer pointing to the topmost element of the
addresses while a module calls another
stack. Whenever an element is added in the stack,
module or functions during execution.
it is added on the top of the stack, and the element
Data space is used to store data, variables, can be deleted only from the stack. In other words,
and constants which are stored by the a stack can be defined as a container in which
program and it is updated during execution.
insertion and deletion can be done from the one
Space Complexity = Auxiliary Space end known as the top of the stack.
+ Input space
It is called as stack because it behaves like a
11. What is Big oh Notation? real-world stack, piles of books, etc.
Ans : A Stack is an abstract data type with a pre-
Big oh Notation (O) defined capacity, which means that it can
Big O notation is an asymptotic notation that store the elements of a limited size.
measures the performance of an algorithm It is a data structure that follows some order
by simply providing the order of growth of to insert and delete the elements, and that
the function. order can be LIFO or FILO.
76
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
a tio
A single stack is sometime not sufficient to store large amount of data. To overcome this problem we
c
l i
can use multiple stack. For this, we have used a single array having more than one stack. The array is
divided for multiple stacks.
b
u
Suppose, there is an array STACK[n] divided into two stack STACK A and STACK B, where
P
ul
n = 10.
STACK A expands from the left to right, i.e. from 0th element.
a h
STACK B expands from the right to left, i.e, from 10th element.
R
The combined size of both STACK A and STACK B never exceed 10.
77
Rahul Publications
B.Sc. II YEAR III SEMESTER
int main()
{
cout<<“Hello”;
cout<<“Student”;
}
As we know, each program has an opening and closing braces; when the opening braces come,
we push the braces in a stack, and when the closing braces appear, we pop the opening braces from the
stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack, it means that some
syntax occurs in a program.
String reversal
Stack is also used for reversing a string. For example, we want to reverse a “Student” string, so we
can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.
UNDO/REDO
c a tio
It can also be used for performing UNDO/REDO operations. For example, we have an editor in
l i
which we write ‘a’, then ‘b’, and then ‘c’; therefore, the text written in an editor is abc. So, there are
b
three states, a, ab, and abc, which are stored in a stack. There would be two stacks in which one
u
stack shows UNDO state, and the other shows REDO state.
P
ul
If we want to perform UNDO operation, and want to achieve ‘ab’ state, then we implement pop
operation.
Recursion
a h
R
The recursion means that the function is calling itself again. To maintain the previous states, the
compiler creates a system stack in which all the previous records of the function are maintained.
DFS(Depth First Search)
This search is implemented on a Graph, and Graph uses the stack data structure.
Backtracking
Suppose we have to create a path to solve a maze problem. If we are moving in a particular path,
and we realize that we come on the wrong way. In order to come at the beginning of the path to
create a new path, we have to use the stack data structure.
Expression conversion
Stack can also be used for expression conversion. This is one of the most important applications of
stack. The list of the expression conversion is given below:
Infix to prefix
Infix to postfix
Prefix to infix
78
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
Prefix to postfix
Postfix to infix
Memory management
The stack manages the memory. The memory is assigned in the contiguous memory blocks. The
memory is known as stack memory as all the variables are assigned in a function call stack memory.
The memory size assigned to the program is known to the compiler. When the function is created,
all its variables are assigned in the stack memory. When the function completed its execution, all the
variables assigned in the stack are released.
16. Explain various types of notations used to evaluate the expression using data structures.
Ans :
The way to write arithmetic expression is known as a notation. An arithmetic expression can be
written in three different but equivalent notations, i.e., without changing the essence or output of an
expression. These notations are -
• Infix Notation
• Prefix (Polish) Notation
• Postfix (Reverse-Polish) Notation
n s
tio
These notations are named as how they use operator in expression. We shall learn the same here in
this chapter.
Infix Notation
l i c a
We write expression in infix notation, e.g. a – b + c, where operators are used in-between
u b
operands. It is easy for us humans to read, write, and speak in infix notation but the same does not go well
with computing devices. An algorithm to process infix notation could be difficult and costly in terms of
time and space consumption.
Prefix Notation
ul P
a h
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
Notation.
Postfix Notation
R
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish
This notation style is known as Reversed Polish Notation. In this notation style, the operator
is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is
equivalent to its infix notation a + b.
The following table briefly tries to show the difference in all three notations -
79
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Polish notation is a notation form for expressing arithmetic, logic and algebraic equations. Its most
basic distinguishing feature is that operators are placed on the left of their operands. If the operator has a
defined fixed number of operands, the syntax does not require brackets or parenthesis to lessen ambiguity.
Polish notation is also known as prefix notation, prefix Polish notation, normal Polish notation, Warsaw
notation and Lukasiewicz notation.
18. What is reverse polish notation?
Ans :
In reverse polish notation, the operator is placed after the operands like xy+, and it is also called
Postfix notation.
In both polish and reverse polish notation we don’t require the parentheses because all the operators
are arranged in their precedence associativity rule.
^ > * = / > - = +
n s
tio
19. Discuss in detail postfix notaion. Write the algorithm to evaluate postfix notation.
Ans :
Postfix Expression
l i c a
b
The postfix expression is an expression in which the operator is written after the operands. For
u
ul P
example, the postfix expression of infix notation ( 2+3) can be written as 23+.
Some key points regarding the postfix expression are:
a h
In postfix expression, operations are performed in the order in which they have written from left to
R
right.
It does not any require any parenthesis.
We do not need to apply operator precedence rules and associativity rules.
Algorithm to evaluate the postfix expression
1. Scan the expression from left to right until we encounter any operator.
2. Perform the operation
3. Replace the expression with its computed value.
4. Repeat the steps from 1 to 3 until no more operators exist.
Let’s understand the above algorithm through an example.
Infix expression: 2 + 3 * 4
We will start scanning from the left most of the expression. The multiplication operator is an operator
that appears first while scanning from left to right. Now, the expression would be:
Expression = 2 + 34*
80
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
= 2 + 12
Again, we will scan from left to right, and the expression would be:
Expression = 2 12 +
= 14
Evaluation of postfix expression using stack.
1. Scan the expression from left to right.
2. If we encounter any operand in the expression, then we push the operand in the stack.
3. When we encounter any operator in the expression, then we pop the corresponding operands
from the stack.
4. When we finish with the scanning of the expression, the final value remains in the stack.
Let’s understand the evaluation of postfix expression using stack.
Example 1: Postfix expression: 2 3 4 * +
n s
c a tio
b l i
P u
a h ul
R
The result of the above expression is 14.
1. Read a character
2. If the character is a digit, convert the character into int and push the integer into the stack.
• Pop the elements from the stack twice obtaining two operands.
81
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
b l i
u
5*4*f(4–1)=20*f(3)
P
ul
20*3*f(3 –1)=60*f(2)
R ah
60*2*f(2–1)=120*f(1)
120*1*f(1–1) = 120*f(0)
120*1=120
22. Transform the following infix expression into the equivalent postfix expression.
Ans :
(i) A + B * (C+D) / F + D * E
A+B*(C+D)F/+D*E
A+B*(C+D)F/+DE*
A+B*(C+D)F/DE*+
A+B(C+D)*F/DE*+
A+BCD*F/+DE*+
ABCD+*F/+DE*+
82
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
(ii) (A+B^D) / (E-F) + G the sequence manner that is organized one after
another in binary format. The File organization in
(A + B^ D) / (E – F) + G
DBMS supports various data operations such as
= (A + B^ D)(E – F)/ + G insert, update, delete, and retrieve the data.
= (A + B^ D)(E – F)/G+ Advantages
= A + BD^(E – F)/G+ The sequential file organization is efficient and
process faster for the large volume of data.
= ABD^+EF-/G+
It is a simple file organization compared to
23. What are the differences between other available file organization methods.
Atomic and composite data with
examples? This method can be implemented using
cheaper storage devices such as magnetic
Ans : tapes.
Atomic Data It requires fewer efforts to store and maintain
data elements.
The Atomic data is the data which is viewed
as single and non decomposable entity by the user. The sequential file organization technique is
Due to its numerical properties, the atomic data can
also be called as Scalar data.
n s
useful for report generation and statistical
computation process.
tio
Example: Consider an integer 5678.It can This file organization is a preferred method
be decomposed into single digit i.e., (5, 6, 7, 8).
However, after decomposition these digits doesn’t
hold the same characteristics as the actual integer
l i c a
for calculating aggregates that involve most
of the data elements that have to be accessed
while performing the computation process.
u
i.e.,(5678)does. Thus,the Atomic data is considered
b Some of the popular use cases are calculating
grades for the students, generating payslips
as single and non decomposable data.
Composite Data
a h
The composite data is defined as the data
which can be decomposed into several meaningful
Disadvantages
R
subfield.It can be also be called as structured data
and it is implemented in C++ by using
structure,class etc..
The shorting operation is a time-consuming
process and more memory space for the
shorted file method in the sequential file
organization.
Example: Consider an employee’s record
The shorting operations iterate for every writes
which contains fields such as employee ID, name,
operation such as insert, update, or delete.
salary etc.. Each employee record is decomposed
into several sub-fields(i.e., employee ID,name, The traversing time is high in the sequential
salary). Thus, the composite data can be file organization as for each writes operation,
decomposed without any change in its meaning. the system or the program control cannot find
a particular data item directly at one go, it
24. What is sequential organization ? Briefly has to traverse through the sequence of data
explain its advantages and dis- items.
advantages.
25. Define a data structure in terms of the
Ans : triplet (D,F,A) give an example.
The Sequential file organization is a popular Ans :
file organization in the database management system
(DBMS). It is a simple technique for file organization The data structure can be defined as the
structure. This technique stores the data element in collection of elements and all the possible operations
83
Rahul Publications
B.Sc. II YEAR III SEMESTER
which are required for those set of elements. Formally data structure can be defined as a data structure is
a set of domains D, a set of domains F and a set of axioms A. this triple (D, F, A) denotes the data
structure d.
26. What are the advantages of prefix and postfix expressions?
Ans :
Advantages of infix
Much easier to translate to a format that is suitable for direct execution. Either format can trivially be
turned into a tree for further processing, and postfix can be directly translated to code if you use a
stack-based processor or virtual machine
Entirely unambiguous. Infix notation requires precedence and associativity rules to disambiguate it,
or addition of extra parentheses that are not usually considered part of the notation. As long as the
number of arguments to each operator are known in advance, both prefix and postfix notation are
entirely unambiguous: “* + 5 6 3” is (5+6)*3, and cannot be interpreted as 5+(6*3), whereas
parenthesis is required to achieve with infix.
Supports operators with different numbers of arguments without variation of syntax. “unary-op 5”
s
and “ternary-op 1 2 3” both work fine, but need special syntax to make them work in infix.
n
tio
Advantages of postfix
Postfix notation is when we use operator after the operands. Let’s discuss the advantages are:
1. Any formula can be expressed without parenthesis.
l i c a
2.
3.
u b
It is very convenient for evaluating formulas on computer with stacks.
Postfix expression doesn’t has the operator precedence.
4.
ul P
Postfix is slightly easier to evaluate.
5.
6.
a h
It reflects the order in which operations are performed.
You need to worry about the left and right associativity.
84
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
2. When the user tries to delete the element from the empty stack then the condition is said to be a
[a]
3.
n s
If the size of the stack is 10 and we try to add the 11th element in the stack then the condition is
tio
known as [c]
(a) Underflow
(c) Overflow
l i a
(b) Garbage collection
c
(d) None of the above
4.
u b
Which one of the following is not the application of the stack data structure [d]
ul P (b) Recursion
(c) Backtracking
5.
(a) Queue R
Which data structure is mainly used for implementing the recursive algorithm?
6. Which data structure is required to convert the infix to prefix notation? [a]
85
Rahul Publications
B.Sc. II YEAR III SEMESTER
9. If the elements ‘1’, ‘2’, ‘3’ and ‘4’ are added in a stack, so what would be the order for the
removal? [c]
(a) 1234 (b) 2134
(c) 4321 (d) None of the above
10. What is the outcome of the prefix expression +, -, *, 3, 2, /, 8, 4, 1? [c]
(a) 12 (b) 11
(c) 5 (d) 4
n s
c a tio
b l i
P u
a h ul
R
86
Rahul Publications
UNIT - I DATA STRUCTURES USING C++
n
tio
10. An is a structure of fixed-size, which can hold items of the same data type.
l i c a
u ANSWESRS
b
1.
2.
Recursion
Data Structure
ul P
3.
a h
Linear order.
4.
5.
R
Algorithm
Unambiguous
6. The time complexity
7. Space complexity
8. Auxiliary space + Input size.
9. Flowchart
10. Array
87
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
A data structure is called linear if all of its elements are arranged in the linear order. In linear data
structures, the elements are stored in non-hierarchical way where each element has the successors and
predecessors except the first and last element.
2. Stack.
Ans :
Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
3. Algorithm.
Ans :
n s
The formal definition of an algorithm is that it contains the finite set of instructions which are being
tio
carried in a specific order to perform the specific task.
4.
Ans :
List any 2 disadvantages of pseudo code.
l i c a
u b
The visual representation of the programming code can be easily understood, and the pseudocode
doesn’t provide it.
ul P
There is no well-defined format to write the pseudocode.
a h
There are no standards available for pseudocode. Companies use their own standards to write it.
If we use pseudocode, we need to maintain one more document for our code.
5.
Ans :
Flow chart?
R
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts
use simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
88
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
2.1 RECURSION
2.1.1 Introduction
Q1. What is Recursion? Explain with an example.
Ans :
n s
The process in which a function calls itself is known as recursion and the corresponding function is
called the recursive function. The popular example to understand the recursion is factorial function.
tio
Factorial function
l i a
f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we will discuss what is base
c
function reaches to the base condition.
u b
In the following diagram. I have shown that how the factorial function is calling itself until the
ul P
Lets say we want to find out the factorial of 5 which means n = 5.
a h
f(5)=5*f(5–1)=5*f(4)
R 5*4*f(4–1)= 20*f(3)
20*3*f(3-1)=60*f(2)
60*2*f(2-1) = 120*f(1)
120*1*f(1-1) = 120*f(0)
120*1=120
#include<iostream>
usingnamespace std;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
89
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
Enter a number: 5
}
Factorial of entered number: 120
Base condition
l i
{ a
intmain()
c
In the above program, you can see that I have
b ... .. ...
Pu
provided a base condition in the recursive function.
The condition is: recursion();
if(n <=1)
ul ... .. ...
ah
return1; }
The figure below shows how recursion works
R
The purpose of recursion is to divide the
problem into smaller problems till the base condition
is reached. For example in the above factorial
program I am solving the factorial function f(n) by
by calling the recursive function again and again.
90
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
voidrecursion()
u b
Indirect recursion
{
... .. ...
ul P When function calls another function and that
function calls the calling function, then this is called
recursion();
}
... .. ...
intmain()
R Example for indirect recursion
#include<iostream>
usingnamespace std;
{ int fa(int);
... .. ... int fb(int);
recursion(); int fa(int n){
... .. ... if(n<=1)
}
return1;
The figure below shows how recursion works
else
by calling the recursive function again and again.
return n*fb(n-1);
There are two types of recursive function i.e.
direct recursion and indirect recursion. Direct }
recursion is when the function calls itself just like we int fb(int n){
saw in the above program. Indirect recursion is when
if(n<=1)
the function calls another function and then that
function calls the calling function. return1;
91
Rahul Publications
B.Sc. II YEAR III SEMESTER
else if((x==1)||(x==0)) {
return n*fa(n-1); return(x);
}
}else {
int main(){
return(fibonnaci(x-1)+fibonnaci(x-2));
int num=5;
cout<<fa(num); }
return0; }
} int main() {
Output int x , i=0;
120 cout <<“Enter the number of terms of
Q4. List out the advantages and disadvan- series : “;
tages of recursion ? cin >> x;
Ans : cout <<“\nFibonnaci Series : “;
Advantages while(i < x) {
Less number code lines are used in the
recursion program and hence the code looks s
cout <<“ “<< fibonnaci(i);
n
tio
i++;
shorter and cleaner.
Recursion is easy to approach to solve the
problems involving data structure and
l i c a }
return0;
algorithms like graph and tree.
b }
Pu
Recursion helps to reduce the time
complexity. Output
ul
It helps to reduce unnecessary calling of the Enter the number of terms of series : 15
ah
function. Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89
It helps to solve the stack evolutions and 144 233 377
R
prefix, infix, postfix evaluation.
Recursion is the best method to define objects
that have repeated structural forms.
Q6. Write a C++ program to find factorial
of given number using recursion.
Disadvantages
Ans :
It consumes a lot of stack space #include <iostream>
It takes more time to process the program using namespace std;
int fact(int n);
If an error is accrued in the program, it is
difficult to debug the error in comparison to int main()
the iterative program. {
Q5. Write a C++ program to print Fibonacci int n;
series using recursion.
cout <<“Enter a positive integer: “;
Ans : cin >> n;
#include <iostream> cout <<“Factorial of “<< n <<“ = “<<
using namespace std; fact(n);
int fibonnaci(int x) { return0;
92
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
}
int fact(int n)
{
if(n >1)
return n * fact(n -1);
else
return1;
}
Output
Enter an positive integer: 6
Factorial of 6 = 720
Q7. Write a c++program to calculate power using recursion in c++.
Ans :
#include <iostream>
n s
using namespace std;
int calculate(int, int);
c a tio
int main()
{
b l i
int base, power, result;
P u
ul
cout <<“Enter base number: “;
cin >> base;
h
cout <<“Enter power number(positive integer): “;
a
R
cin >> power;
result = calculate(base, power);
cout << base <<“^”<< power <<“ = “<< result;
return0;
}
int calculate(int base, int power)
{
if (power !=0)
return (base*calculate(base, power-1));
else
return1;
}
Output
Enter base number: 3
Enter power number (positive integer): 4
3^4 = 81
93
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
cout <<“No, Number is not Prime
Number”;
int main()
{
b l i
}
return0;
int n,reverse;
cout<<“Enter number”;
ul Pu Output
No, Number is not Prime Number
ah
cin >> n; 2.1.2 Recurrence
reverse = reverseNumber(n);
return0;
R
cout <<“Reverse of number is”<< reverse;
Q10. Define Recurrence.
Ans :
Recurrence means, the number of times, that
}
a function has recused. It may also mean, simply,
Output that something has been repeated. It may even be
Enter number : 3456 a variable.
Reverse of number is : 6543 A recurrence is a well-defined mathematical
Q9. Write a C++ program to check whether function where the function being defined is applied
the given number is a prime or not using within its own definition. The mathematical function
recursion. factorial of n can also be defined recursively as n! =
n × (n - 1)!, where 1! = 1 Fibonacci sequence as
Ans : an example. The Fibonacci sequence is the
sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34,
#include <bits/stdc++.h>
55, ... The first two numbers of the sequence are
using namespace std; both 1, whereas each succeeding number is the sum
bool isprime(int n, int i =2) of the preceding two numbers (we arrived at 55 as
the 10th number; it is the sum of 21 and 34, the
{ eighth and ninth numbers).
94
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
2.1.3 Use of Stack in Recursion Step 2: Element 4 is pushed at the bottom of the
stack shown as below:
Q11. Explain how recursion used to reversing
the stack?
Ans :
There are various ways to reverse a stack
using recursion. The most common way of reversing
a stack is to use an auxiliary stack. First, we will pop Step 3: Element 3 is pushed at the bottom of the
all the elements from the stack and push them into stack shown as below:
the auxiliary stack. Once all the elements are pushed
into the auxiliary stack, then it contains the elements
in the reverse order and we simply print them. But,
here, we will not use the auxiliary stack. We will use
a recursion method to reverse a stack where
recursion means calling the function itself again and
again. Step 4: Element 2 is pushed at the bottom of the
In the recursion method, we first pop all the stack shown as below:
elements from the input stack and push all the
popped items into the function call stack until the
n s
tio
stack becomes empty. When the stack becomes
empty, all the items will be pushed at the stack. Let’s
understand this scenario through an example.
For example:
l i c a
Input stack: 1, 2, 3, 4, 5
u b
Step 5: Element 1 is pushed at the bottom of the
stack shown as below:
ul P
a h
R
Q12. Write an algorithm to sort a stack.
Ans :
Output: 5, 4, 3, 2, 1 1. Initialize a stack and push elements in it.
Solution 2. Create a function to insert the elements in
Firstly, all the elements from the input stack sorted order in the stack which accepts a stack
are pushed into the function call stack and an element as a parameter. Check if the
stack is empty or the given element is greater
Step 1: Element 5 is pushed at the bottom of the
than the element at the top of the stack, push
stack shown as below:
the element in the stack and return.
3. Create a temporary variable and store the
top of the stack in it. Pop the element at the
top of the stack and make the recursive call
to the function itself. Push the temporary
variable in the stack.
95
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
usingnamespacestd; void Stack::Disp ()
structNODE {
{
int Data;
l i c a NODE *Temp = Top;
while (Temp != NULL)
NODE *Next;
u b {
};
classStack
ah
{ }
NODE *Top; }
{
public:
Stack ()R void Stack::ISort (Stack & A, int t)
{
NODE *Temp = Top;
Top = NULL; if (Top == NULL || Top->Data > t)
} A.Push (t);
voidPush (int x); //If Stack empty,insert the element or t
intPop (); // is smaller than Top
voidDisp (); else
voidISort (Stack & A, int t); {
voidSort (Stack & A); int x = A.Pop (); // Pop the Top element
}; ISort (A, t); // Sorting
void Stack::Push (int x) A.Push (x); // Pushing all the popped
{ // elements
NODE *Temp; }
Temp = new NODE; }
Temp->Data = x; void Stack :: Sort (Stack &A)
96
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
In the above syntax, the main() function calls
tio
ST.Push (11); the recursion function only once. After that, the
ST.Disp (); recursion function calls itself up to the defined
cout<<“Sorted List\n”;
ST.Sort(ST);
l i c a
condition, and if the user doesn’t define the
condition, it calls the same function infinite times.
ST.Disp();
u b Recursive functions can be classified on the
basis of :
return0;
}
ah
Output
b) If an operation is pending at each recursive
R c)
call – Tail Recursive/ Not
based on the structure of the function calling
pattern – Linear / Tree
(i) Direct Recursion
If a function explicitly calls itself it is called
directly recursive.
When the method invokes itself it is direct.
int testfunc(int num) {
2.1.4 Variants of Recursion , Recursive
functions if (num == 0)
97
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
} It is linearly recursive when, the pending
opera-tions do not involve another recursive call to
(iii) Tail / Bottom Recursion
A function is said to be tail-recursive, if no
l i a
the function. Our Factorial recursive function is
c
linearly recursive as it only involves multiplying the
operations are pending when the recursive function
returns to its caller.
u b returned values and no further calls to function.
Tree recursion is when, pending operations
ul P
Such functions, immediately return the return
value from the calling function.
involve another recursive call to function.
Q15. What is recursive function?
h
It is an efficient method as compared to others,
a
as the stack space required is less and even
Ans :
R
compute overhead will get reduced.
Recollect the previously discussed example,
factorial of a number. We had written it in
Recursive Functions
Recursive Functions is the process of
defining something in terms of itself. It is a function
that calls itself again in the body of the function.
non tail recursive way, as after call operation
A function fact ( ), that computes the factorial
is still pending.
of an integer ‘N’ ,which is the product of all whole
int fact(int n){ numbers from 1 to N.
if (n == 1) When fact ( ) is called with an argument of 1
return 1; (or) 0, the function returns 1. Otherwise, it returns
the product of n*fact (n-1), this happens until ‘n’
else equals 1.
return (n * fact(n - 1)); Fact (5) = 5* fact (4)
} = 5*4*3* fact (3)
In order to make it tail recursive, information = 5*4*3*2* fact (2)
about pending tasks has to be tracked.
= 5*4*3*2*1 fact (1)
int fact(int n){ = 5*4*3*2*1
return (n * fact2(n - 1)); = 120.
98
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
c a tio
b l i
P u
a h ul
R
99
Rahul Publications
B.Sc. II YEAR III SEMESTER
Program
#include<iostream.h>
#include<conio.h>
usingnamespace std;
void TOH(int d, char t1, char t2, char t3)
{
if(d==1)
{
cout<<“\nShift top disk from tower” <<t1<<“ to tower”<<t2;
return;
}
TOH(d-1,t1,t3,t2);
cout<<“\nShift top disk from tower” <<t1 <<“ to tower”<<t2;
TOH(d-1,t3,t2,t1);
}
int main()
n s
tio
{
int disk;
cout<<“Enter the number of disks:”; cin>>disk;
if(disk<1)
l i c a
u
cout<<“There are no disks to shift”;
b
else
ul P
cout<<“There are “<<disk<<“disks in tower 1\n”;
a h
TOH(disk, ‘1’,’2',’3');
cout<<“\n\n”<<disk<<“disks in tower 1 are shifted to tower 2”;
getch();
return0;
}
R
Output
Enter the number of disks: 3
There are 3 disks in tower 1
Shift top disk from tower 1 to tower 2
Shift top disk from tower 1 to tower 3
Shift top disk from tower 2 to tower 3
Shift top disk from tower 1 to tower 2
Shift top disk from tower 3 to tower 1
Shift too disk from tower 3 to tower 2
Shift top disk from tower 1 to tower 2
3 disks in tower 1 are shifted to tower 2
100
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans :
Iteration uses repetition structure.
An infinite loop occurs with iteration if the loop condition test never becomes false and Infinite
looping uses CPU cycles repeatedly.
An iteration terminates when the loop condition fails.
An iteration does not use the stack so it’s faster than recursion.
Iteration consumes less memory.
Iteration makes the code longer.
Q18. What are the differences between Iteration and recursion.
Ans :
On the basis Recursion Iteration
Basic Recursion is the process of calling
n s
In iteration, there is a repeated execution of the
tio
a function itself within its own code. set of instructions. In Iteration, loops are used
to execute the set of instructions repetitively until
Pu
Termination The termination condition is defined Here, the termination condition is defined in the
within the recursive function. definition of the loop.
Code size
ul
The code size in recursion is smaller The code size in iteration is larger than the code
ah
than the code size in iteration. size in recursion.
Infinite If the recursive function does not Iteration will be infinite, if the control condition of
101
Rahul Publications
B.Sc. II YEAR III SEMESTER
2.2 QUEUES
n s
tio
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first,
exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
Queue Representation
l i c a
u b
As we now understand that in queue, we access both ends for different reasons. The following
diagram given below tries to explain queue representation as data structure:
ul P
a h
R
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.
For the sake of simplicity, we shall implement queues using one-dimensional array.
A queue in the data structure can be considered similar to the queue in the real-world. A queue is
a data structure in which whatever comes first will go out first. It follows the FIFO (First-In-First-Out)
policy. In Queue, the insertion is done from one end known as the rear end or the tail of the queue,
whereas the deletion is done from another end known as the front end or the head of the queue. In other
words, it can be defined as a list or a collection with a constraint that the insertion can be performed at one
end called as the rear end or tail of the queue and deletion is performed on another end called as the
front end or the head of the queue.
102
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Operations on Queue
There are two fundamental operations
performed on a Queue:
Enqueue: The enqueue operation is used to
insert the element at the rear end of the
queue. It returns void.
Dequeue: The dequeue operation performs
the deletion from the front-end of the queue.
It also returns the element which has been
removed from the front-end. It returns an
integer value. The dequeue operation can
also be designed to void.
Peek: This is the third operation that returns
the element, which is pointed by the front
pointer in the queue but does not delete it.
Queue overflow (isfull): When the Queue
n s
tio
is completely full, then it shows the overflow
condition.
Queue underflow (isempty): When the
Queue is empty, i.e., no elements are in the
l i c a
Queue then it throws the underflow
u b
condition.
Q20. Explain Enqueue
ul
andP Dequeue
Ans :
operations.
a h
Enqueue Operation
R
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.
103
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
returns nothing. if (front == -1) front = 0;
dequeue() removes the front item from rear++;
the queue. It needs no parameters and
returns the item. The queue is modified.
l i c a
items[rear] = element;
cout << endl
isEmpty() tests to see whether the queue
u
is empty. It needs no parameters and b << “Inserted “ << element << endl;
returns a boolean value.
ul P
size() returns the number of items in the
}
}
a h
queue. It needs no parameters and
returns an integer.
int deQueue() {
int element;
Ans :
Queue ADT. R
Q22. Write a C++ program to implement
(June-18, Dec.-17)
if (isEmpty()) {
cout << “Queue is empty” << endl;
return (-1);
} else {
// Queue implementation in C++ element = items[front];
#include <iostream> if (front >= rear) {
#define SIZE 5 front = -1;
using namespace std; rear = -1;
class Queue { } /* Q has only one element, so we reset the
private: queue after deleting it. */
int items[SIZE], front, rear; else {
public: front++;
Queue() { }
front = -1; cout << endl
rear = -1; << “Deleted -> “ << element << endl;
} return (element);
104
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n
tio
the rear and removal occurs at the front. It
} strictly follows the FIFO (First in First out) rule.
};
}
l i c a
int main()
b
Pu
{ Circular Queue
Queue q;
ul
//deQueue is not possible on empty queue
In a circular queue, the last element points to
ah
the first element making a circular link.
q.deQueue();
R
//enQueue 5 elements
q.enQueue(1);
q.enQueue(2);
Circular Queue Representation
q.enQueue(3);
q.enQueue(4); The main advantage of a circular queue over
q.enQueue(5); a simple queue is better memory utilization.
// 6th element can’t be added to because the If the last position is full and the first position
//queue is full is empty, we can insert an element in the first
position. This action is not possible in a simple
q.enQueue(6);
queue.
q.display();
// deQueue removes element entered first i.e. 1 Priority Queue
q.deQueue(); A priority queue is a special type of queue in
//Now we have just 4 elements which each element is associated with a
q.display(); priority and is served according to its priority.
If elements with the same priority occur, they
return 0; are served according to their order in the
} queue.
105
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Deque Representation
tio
After deleting an element, the value of front
a
will increase from -1 to 0. however, the queue will
c
2.2.2 Realization of Queues using Arrays
Q24. Explain queue implementation using
b l i
look something like following.
Ans :
arrays.
P u
Array representation of Queue
a h ul
We can easily represent queue by using linear
R
arrays. There are two variables i.e. front and rear,
that are implemented in the case of every queue.
Front and rear variables point to the position from
where insertions and deletions are performed in a
queue. Initially, the value of front and queue is -1
which represents an empty queue. Array Q25. Explain Enqueue(), DeQueue(), Display()
representation of a queue containing 5 elements operations.
along with the respective values of front and rear, is Ans :
shown in the following figure.
Before we implement actual operations, first
follow the below steps to create an empty queue.
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 user defined functions
which are used in queue implementation.
Step 3: Create a one dimensional array with
above defined SIZE (int queue[SIZE]).
106
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Step 4: Define two integer variables ‘front’ display() - Displays the elements of a Queue
and ‘rear’ and initialize both with ‘–1’. (int
We can use the following steps to display the
front = -1, rear = -1)
elements of a queue...
Step 5: Then implement main method by Step 1: Check whether queue is EMPTY.
displaying menu of operations list and make (front == rear)
suitable function calls to perform operation
selected by the user on queue. Step 2: If it is EMPTY, then display “Queue
is EMPTY!!!” and terminate the function.
enQueue(value) - Inserting value into the
queue Step 3: If it is NOT EMPTY, then define an
integer variable ‘i’ and set ‘i = front+1’.
In a queue data structure, enQueue() is a
function used to insert a new element into the queue. Step 4: Display ‘queue[i]’ value and
In a queue, the new element is always inserted increment ‘i’ value by one (i++). Repeat the
at rear position. The enQueue() function takes one same until ‘i’ value reaches to rear (i <=
integer value as a parameter and inserts that value rear).
into the queue. We can use the following steps to Q26. Write an algorithm to insert an element
insert an element into the queue... to the queue and delete an element from
Step 1: Check whether queue is FULL.
(rear == SIZE-1) Ans :
the queue.
n s
Step 2: If it is FULL, then display “Queue
is FULL!!! Insertion is not possible!!!” and
tio
Algorithm to insert any element in a queue
c a
terminate the function.
Step 3: If it is NOT FULL, then increment l i Check if the queue is already full by
comparing rear to max - 1. if so, then return an
b
overflow error.
Pu
rear value by one (rear++) and set
queue[rear] = value. If the item is to be inserted as the first element
ul
deQueue() - Deleting a value from the Queue
in the list, in that case set the value of front and rear
to 0 and insert the element at the rear end.
R ah
In a queue data structure, deQueue() is a
function used to delete an element from the queue.
In a queue, the element is always deleted
from front position. The deQueue() function does
Otherwise keep increasing the value of rear
and insert each element one by one having rear as
the index.
107
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
n s
tio
Some drawbacks of using this technique to implement a queue.
Memory wastage
l i c a
The space of the array, which is used to store queue elements, can never be reused to store the
u b
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.
ul P
a h
R
The above figure shows how the memory space is wasted in the array representation of queue. In
the above figure, a queue of size 10 having 3 elements, is shown. The value of the front variable is 5,
therefore, we can not reinsert the values in the place of already deleted element before the position of
front. That much space of the array is wasted and can not be used in the future (for this queue).
Deciding the array size
On of the most common problem with array implementation is the size of the array which requires
to be declared in advance. Due to the fact that, the queue can be extended at runtime depending upon
the problem, the extension in the array size is a time taking process and almost impossible to be performed
at runtime since a lot of reallocations take place. Due to this reason, we can declare the array large enough
so that we can store queue elements as enough as possible but the main problem with this declaration is
that, most of the array slots (nearly half) can never be reused. It will again lead to memory wastage.
108
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
case3:Display();
tio
rear++; break;
}
queue[rear]= val;
l i c a case4: cout<<“Exit”<<endl;
break;
}
voidDelete(){
u b default: cout<<“Invalid choice”<<
endl;
ul P
if(front ==-1|| front > rear){
cout<<“Queue Underflow “;
}
}while(ch!=4);
return;
a h return0;
}else{
R
cout<<“Element deleted from queue is :
“<< queue[front]<<endl;
}
1)
The output of the above program is as follows
Insert element to queue
front++;; 2) Delete element from queue
}
3) Display all the elements of queue
}
4) Exit
voidDisplay(){
if(front ==-1) Enter your choice : 1
cout<<“Queue is empty”<<endl; Insert the element in queue : 4
else{ Enter your choice : 1
cout<<“Queue elements are : “; Insert the element in queue : 3
for(int i = front; i <= rear; i++) Enter your choice : 1
cout<<queue[i]<<“ “; Insert the element in queue : 5
cout<<endl; Enter your choice : 2
} Element deleted from queue is : 4
} Enter your choice : 3
109
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Linked representation of queues is the
tio
end. effective and proper utilization of memory.
A Queue is logically a First in First Out (FIFO)
type of data structure Or Queue simply means a
l i a
There is no memory wasted in linked lists
c
because the data elements are stored at distant
line and follows FIFO logical design, which means
u
the element inserted first will be deleted first.
b
places in the memory whose addresses are linked
by pointers.
ul P
Implementing Queues using Pointers is an
effective way of the utilization of memory.
Time efficient
There is no need to worry about deleting the
a h
Since it is dynamic therefore you don’t need
to worry about the size of the queue It will grow
element in the middle because it requires same
amount of time to Insert at front and middle.
R
and shrink at the run time.
In Arrays, if you want to add or delete
elements in the middle then you have to shift all
It is a very useful data structure that is used in
various aspects of programming fields and in the
software development process.
the existing elements.
Example
But in Linked Lists, You only have to insert a
#include<iostream>
new node and adjust the links of the newly inserted
node with the rest of the nodes. usingnamespace std;
struct node {
Algorithm for Insertion
Queue_Linked Ptr, temp int data;
Temp=start struct node *next;
Ptr=new node };
Ptr->data=NULL struct node* front = NULL;
If Rear == NULL struct node* rear = NULL;
Set front=Ptr struct node* temp;
Set rear=Ptr voidInsert(){
Else int val;
110
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
tio
}
cout<<“4) Exit”<<endl;
voidDelete(){
temp = front;
if(front == NULL){
l
do{
i c a
cout<<“Enter your choice : “<<endl;
cout<<“Underflow”<<endl;
u b cin>>ch;
switch(ch){
}
return;
ul P case1:Insert();
break;
else
a
if(temp->next!= NULL){ h case2:Delete();
R
temp = temp->next;
cout<<“Element deleted from queue is :
“<<front->data<<endl;
break;
case3:Display();
break;
free(front); case4: cout<<“Exit”<<endl;
front = temp; break;
}else{ default: cout<<“Invalid choice”<<endl;
cout<<“Element deleted from queue is : }
“<<front->data<<endl; }while(ch!=4);
free(front); return0;
front = NULL; }
rear = NULL; Output
} The output of the above program is as follows
} 1) Insert element to queue
voidDisplay(){ 2) Delete element from queue
temp = front; 3) Display all the elements of queue
if((front == NULL)&&(rear == NULL)){ 4) Exit
111
Rahul Publications
B.Sc. II YEAR III SEMESTER
Enter your choice : 1 As we can see in the above image, the rear is
Insert the element in queue : 4 at the last position of the Queue and front is pointing
somewhere rather than the 0 th position. In the
Enter your choice : 1
above array, there are only two elements and other
Insert the element in queue : 3 three positions are empty. The rear is at the last
Enter your choice : 1 position of the Queue; if we try to insert the element
Insert the element in queue : 5 then it will show that there are no empty spaces in
Enter your choice : 2 the Queue. There is one solution to avoid such
wastage of memory space by shifting both the
Element deleted from queue is : 4 elements at the left and adjust the front and rear
Enter your choice : 3 end accordingly. It is not a practically good approach
Queue elements are : 3 5 because shifting all the elements will consume lots
Enter your choice : 7 of time. The efficient approach to avoid the wastage
of the memory is to use the circular queue data
Invalid choice
structure.
Enter your choice : 4
Q31. Discuss the operations and applications
Exit
of circular queue.
2.2.3 Circular Queue, Multi Queues
Q30. What is mean by Circular Queue? What
Ans :
n s (July-21)
tio
Operations on Circular Queue
is the need of circular queue?
The following are the operations that can be
Ans : (July-21, Dec.-19)
A circular queue is similar to a linear queue
l i c a
performed on a circular queue:
Front: It is used to get the front element from
as it is also based on the FIFO (First In First Out)
b the Queue.
Pu
principle except that the last position is connected Rear: It is used to get the rear element from
ul
to the first position in a circular queue that forms a
circle. It is also known as a Ring Buffer.
the Queue.
enQueue(value): This function is used to
ah
There was one limitation in the array insert the new value in the Queue. The new
implementation of Queue.
R
If the rear reaches to the end position of the
Queue then there might be possibility that some
vacant spaces are left in the beginning which cannot
element is always inserted from the rear end.
deQueue(): This function deletes an
element from the Queue. The deletion in a
Queue always takes place from the front end.
be utilized. So, to overcome such limitations, the
concept of the circular queue was introduced. Applications of Circular Queue
The circular Queue can be used in the
following scenarios:
Memory management
The circular queue provides memory
management. As we have already seen that in linear
queue, the memory is not managed very efficiently.
But in case of a circular queue, the memory is
managed efficiently by placing the elements in a
location which is unused.
CPU Scheduling
The operating system also uses the circular
queue to insert the processes and then execute them.
112
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
The steps of enqueue operation are given SET REAR = (REAR + 1) % MAX
below: [END OF IF]
n s
tio
First, we will check whether the Queue is full Step 3: SET QUEUE[REAR] = VAL
or not.
Step 4: EXIT
Initially the front and rear are set to -1. When
we insert the first element in a Queue, front
l i c a
Dequeue Operation
ul P
When we insert a new element, the rear gets
incremented, i.e., rear = rear + 1.
First, we check whether the Queue is empty
or not. If the queue is empty, we cannot
a h
Scenarios for inserting an element
perform the dequeue operation.
When the element is deleted, the value of
not full:
R
There are two scenarios in which queue is
113
Rahul Publications
B.Sc. II YEAR III SEMESTER
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT
Let’s understand the enqueue and dequeue
operation through the diagrammatic representation.
n s
c a tio
b l i
P u
a h ul Q33. Write a C++ program to implement
Circular Queue .
R Ans :
#include<iostream>
usingnamespace std;
int cqueue[5];
int front =-1, rear =-1, n=5;
void insertCQ(int val){
if((front ==0&& rear == n-1)||(front ==
rear+1)){
cout<<“Queue Overflow \n”;
return;
}
if(front ==-1){
front =0;
rear =0;
114
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
}else{ do{
if(rear == n -1) cout<<“Enter choice : “<<endl;
rear =0; cin>>ch;
else switch(ch){
rear = rear +1; case1:
} cout<<“Input for insertion: “<<endl;
cqueue[rear]= val ; cin>>val;
} insertCQ(val);
void deleteCQ(){ break;
if(front ==-1){ case2:
cout<<“Queue Underflow\n”; deleteCQ();
return; break;
}
cout<<“Element deleted from queue is :
case3:
displayCQ();
n s
tio
“<<cqueue[front]<<endl;
break;
if(front == rear){
front =-1;
l i c a case4:
rear =-1;
b cout<<“Exit\n”;
Pu
}else{cout<<cqueue[f]<<“ “; break;
f++;
ul default: cout<<“Incorrect!\n”;
ah
} }
}while(ch !=4);
}else{
R
while(f <= n -1){
cout<<cqueue[f]<<“ “; }
return0;
f++; Output
f =0; 1) Insert
cout<<cqueue[f]<<“ “; 3) Display
115
Rahul Publications
B.Sc. II YEAR III SEMESTER
Input for insertion: deletion can be performed only from one end;
therefore, we conclude that dequeue can be
Enter choice : 1
considered as a stack.
Input for insertion:
In deque, the insertion can be performed on
Enter choice : 1 one end, and the deletion can be done on another
Input for insertion: end. The queue follows the FIFO rule in which the
element is inserted on one end and deleted from
Enter choice : 2 another end. Therefore, we conclude that the deque
Element deleted from queue is : 5 can also be considered as the queue.
tio
restricted queue means that some restrictions
Queue elements are :
are applied to the deletion operation. In an
796
Enter choice : 4
l i c a
output-restricted queue, the deletion can be
applied only from one end, whereas the
Pu
Exit
Q35. List out the operations and apllications
of Dequeue.
2.2.4 Dequeue, Priority Queue
ul
Q34. Explain in detail about Dequeue. Ans :
Ans :
R ah (Dec.-19)
The dequeue stands for Double Ended
Queue. In the queue, the insertion takes place from
The following are the operations applied on
deque:
Insert at front
one end while the deletion takes place from another Delete from end
end. The end at which the insertion occurs is known insert at rear
as the rear end whereas the end at which the
delete from rear
deletion occurs is known as front end.
Other than insertion and deletion, we can also
Deque is a linear data structure in which the perform peek operation in deque. Through peek
insertion and deletion operations are performed operation, we can get the front and the rear
from both ends. We can say that deque is a element of the dequeue.
generalized version of the queue.
We can perform two more operations on
Properties of deque dequeue:
Deque can be used both as stack and queue isFull(): This function returns a true value
as it allows the insertion and deletion operations on if the stack is full; otherwise, it returns a false
both ends. value.
In deque, the insertion and deletion operation isEmpty(): This function returns a true value
can be performed from one side. The stack follows if the stack is empty; otherwise it returns a
the LIFO rule in which both the insertion and false value.
116
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
If the front is pointing to the last element of
the array, and we want to perform the delete
tio
operation from the front. To delete any
all its threads then it steals the thread from
element from the front, we need to
the rear end of the processor P1 and adds to
the front end of the processor P 2. The
processor P2 will take the thread from the
l i c a
set front=front+1. Currently, the value of
the front is equal to 4, and if we increment
front end; therefore, the deletion takes from
u
both the ends, i.e., front and rear end. This b the value of front, it becomes 5 which is not
a valid index. Therefore, we conclude that if
ul P
is known as the A-steal algorithm for
scheduling.
front points to the last element, then front is
set to 0 in case of delete operation.
h
Q36. Explain Enqueue and Dequeue opera-
a
tions in detail.
2. If we want to delete the element from rear
end then we need to decrement the rear value
Ans : R
The following are the steps to perform the 3.
by 1, i.e., rear=rear-1 as shown in the
below figure:
If the rear is pointing to the first element, and
operations on the Deque: we want to delete the element from the rear
end then we have to set rear=n-1 where n is
Enqueue operation the size of the array as shown in the below
1. Initially, we are considering that the deque is figure:
empty, so both front and rear are set to -1, Q37. Write a C++ program for Deque
i.e., f = -1 and r = -1. implementation.
2. As the deque is empty, so inserting an element
Ans :
either from the front or rear end would be
the same thing. Suppose we have inserted #include<iostream>
element 1, then front is equal to 0, and usingnamespace std;
the rear is also equal to 0.
#define SIZE 10
3. Suppose we want to insert the next element class dequeue {
from the rear. To insert the element from the
int a[20],f,r;
rear end, we first need to increment the rear,
i.e., rear=rear+1. Now, the rear is pointing public:
117
Rahul Publications
B.Sc. II YEAR III SEMESTER
l i c a
}
f=f+1;
f++;
u b }
}else{
r++;
ul P void dequeue::delete_fr_rear(){
if(f==-1){
ah
r=r+1;
cout<<“deletion is not possible::dequeue is
}
a[r]=i; R
cout<<“\nInserted item is”<<a[r];
empty”;
return;
}
} else{
} cout<<“the deleted element is:”<<a[r];
void dequeue::insert_at_beg(int i){ if(f==r){
if(f==-1){ f=r=-1;
f=0; }else
a[++r]=i; r=r-1;
cout<<“\n inserted element is:”<<i; }
}elseif(f!=0){ }
a[—f]=i; void dequeue::show(){
cout<<“\n inserted element is:”<<i; if(f==-1){
}else{ cout<<“Dequeue is empty”;
118
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
}else{ break;
for(int i=f;i<=r;i++){ case5:
cout<<a[i]<<“ “; d.delete_fr_rear();
} break;
} case6:
} exit(1);
int main(){ break;
int c,i; default:
dequeue d; cout<<“invalid choice”;
Do//perform switch opeartion { break;
c a
insert at end
tio
insert at beginning
b
4.l i show
deletion from front
Pu
cin>>c;
5. deletion from rear
switch(c){
case1:
ul 6. exit
ah
enter your choice: 1
cout<<“enter the element to be inserted”; deletion is not possib
cin>>i;
R
d.insert_at_beg(i);
1.
3.
nsert at end
show
break; 4. deletion from front
case2: 5. deletion from rear
cout<<“enter the element to be inserted”; 6. exit
cin>>i; enter your choice:5
d.insert_at_end(i); deletion is not possible::dequeue is empty
break; 1. insert at beginning
case3: 2. insert at end
d.show(); 3. show
break; 4. deletion from front
case4: 5. deletion from rear
d.delete_fr_front(); 6. exit
119
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
3. show 5. deletion from rear
6. exit
4.
5.
deletion from front
deletion from rear
l i c a
enter your choice:4
6. exit
enter your choice:1
u b
the deleted element is:7
1. insert at beginning
ul P 2.
3.
insert at end
show
ah
insertion is not possible, overflow!!!
4. deletion from front
1. insert at beginning
2.
3. show
R
insert at end
5.
6.
deletion from rear
exit
enter your choice:5
4. deletion from front the deleted element is:4
5. deletion from rear 1. insert at beginning
6. exit 2. insert at end
enter your choice:2 3. show
enter the element to be inserted6 4. deletion from front
Inserted item is6 5. deletion from rear
1. insert at beginning 6. exit
2. insert at end enter your choice:1
3. show enter the element to be inserted7
4. deletion from front inserted element is:7
5. deletion from rear 1. insert at beginning
6. exit 2. insert at end
120
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
u
with the highest priority would come first in a priority b In descending order priority queue, a higher
priority number is given as a higher priority in a
P
queue. The priority of the elements in a priority
ul
queue will determine the order in which elements
are removed from the priority queue.
priority. For example, we take the numbers from 1
to 5 arranged in descending order like 5, 4, 3, 2, 1;
therefore, the largest number, i.e., 5 is given as the
a h
The priority queue supports only comparable
highest priority in a priority queue.
R
elements, which means that the elements are either
arranged in an ascending or descending order.
For example, suppose we have some values
Element with the
lowest priority
121
Rahul Publications
B.Sc. II YEAR III SEMESTER
In the case of priority queue, lower priority number is considered the higher priority, i.e., lower
priority number = higher priority.
Step 1
In the list, lower priority number is 1, whose data value is 333, so it will be inserted in the list as
shown in the below diagram:
n s
tio
Step 2
a
After inserting 333, priority number 2 is having a higher priority, and data values associated with
c
this priority are 222 and 111. So, this data will be inserted based on the FIFO principle; therefore 222 will
be added first and then 111.
l i
Step 3
u b
ul P
After inserting the elements of priority 2, the next higher priority number is 4 and data elements
associated with 4 priority numbers are 444, 555, 777. In this case, elements would be inserted based on
Step 4
a h
the FIFO principle; therefore, 444 will be added first, then 555, and then 777.
R
After inserting the elements of priority 4, the next higher priority number is 5, and the value associated
with priority 5 is 666, so it will be inserted at the end of the queue.
122
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans :
#include<iostream>
#include<queue>
usingnamespace std;
void dequeElements(priority_queue <int> que){
priority_queue <int> q = que;
while(!q.empty()){
cout << q.top()<<“ “;
q.pop();
}
cout << endl;
}
int main(){
priority_queue <int> que;
n s
que.push(10);
que.push(20);
c a tio
que.push(30);
que.push(5);
b l i
que.push(1);
P u
ul
cout <<“Currently que is holding : “;
a h
dequeElements(que);
cout <<“Size of queue : “<<que.size()<< endl;
R
cout <<“Element at top position : “<< que.top()<< endl;
cout <<“Delete from queue : “;
que.pop();
dequeElements(que);
cout <<“Delete from queue : “;
que.pop();
dequeElements(que);
}
Output
Currently que is holding : 30 20 10 5 1
Size of queue : 5
Element at top position : 30
Delete from queue : 20 10 5 1
Delete from queue : 10 5 1
123
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Applications of Queue
Due to the fact that queue performs actions on first in first out basis which is quite fair for the
ordering of actions. There are various applications of queues discussed as below.
1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred at the same
rate between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
4. Queue are used to maintain the play list in media players in order to add and remove the songs
from the play-list.
5. Queues are used in operating systems for handling interrupts.
Q42. What are the differences between stack and Queue.
Ans :
n s
Basis for
comparison
Stack
c a tio Queue
Principle
b l
It follows the principle LIFO (Last
i It follows the principle FIFO (First In -
P u
In-First Out), which implies that the
element which is inserted last would
First Out), which implies that the
element which is added first would
ul
be the first one to be deleted. be the first element to be removed
from the list.
Structure
R ah
It has only one end from which both
the insertion and deletion take place,
and that end is known as a top.
It has two ends, i.e., front and rear end.
The front end is used for the deletion
while the rear end is used for the insertion.
Number of It contains only one pointer known It contains two pointers front and rear
pointers as a top pointer. The top pointer holds pointer. The front pointer holds the
used the address of the last inserted or the address of the first element, whereas
topmost element of the stack. the rear pointer holds the address of
the last element in a queue.
Operations It performs two operations, push and It performs mainly two operations,
performed pop. The push operation inserts the enqueue and dequeue. The enqueue
element in a list while the pop oper- operation performs the insertion of
ation removes the element from the the elements in a queue while
list. the dequeue operation performs
the deletion of the elements from
the queue.
Examination If top==-1, which means that the If front== -1 or front = rear +1,
of the empty stack is empty. which means that the queue is
condition empty.
124
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans :
Basis of comparison Linear Queue Circular Queue
Meaning The linear queue is a type of linear The circular queue is also a
data structure that contains the linear data structure in which
elements in a sequential manner.
s
the last element of the Queue
n
tio
is connected to the first
element, thus creating a circle.
Insertion and Deletion
li c a
In linear queue, insertion is done
from the rear end, and deletion is
In circular queue, the insertion
and deletion can take place
Memory space
u b
done from the front end.
The memory space occupied by the
from any end.
It requires less memory as
ul P
linear queue is more than the
circular queue.
compared to linear queue.
ah
Memory utilization The usage of memory is inefficient. The memory can be more
efficiently utilized.
R
Order of execution It follows the FIFO principle in order
to perform the tasks.
It has no specific order for
execution.
Q44. What is Linked List? List out the advantages and disadvantages of linked list.
Ans :
When we want to work with an unknown number of data values, we use a linked list data structure
to organize that data. The linked list is a linear data structure that contains a sequence of elements such
that each element links to its next element in the sequence. Each element in a linked list is called “Node”.
These elements are linked to each other by providing one additional information along with an
element, i.e., the address of the next element. The variable that stores the address of the next element is
known as a pointer. Therefore, we conclude that the linked list contains two parts, i.e., the first one is the
data element, and the other is the pointer.
125
Rahul Publications
B.Sc. II YEAR III SEMESTER
A linked list can also be defined as the collection of the nodes in which one node is connected to
another node, and node consists of two parts, i.e., one is the data part and the second one is the address
part, as shown in the below figure:
In the above figure, we can observe that each node contains the data and the address of the next
node. The last node of the linked list contains the NULL value in the address part.
A linked-list is a sequence of data structures which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another
link. Linked list the second most used data structure after array. Following are important terms to understand
the concepts of Linked List.
n s
tio
Link: Each Link of a linked list can store a data called an element.
i a
Next: Each Link of a linked list contain a link to next link called Next.
c
LinkedList: A LinkedList contains the connection link to the first Link called First.
l
Linked List Representation
u b
ul P
a h
R
As per above shown illustration, following are the important points to be considered.
LinkedList contains an link element called first.
Each Link carries a data field(s) and a Link Field called next.
Each Link is linked with its next link using its next link.
Last Link carries a Link as null to mark the end of the list.
The following are the advantages of using a linked list over an array:
Dynamic data structure
The size of the linked list is not fixed as it can vary according to our requirements.
Insertion and Deletion
Insertion and deletion in linked list are easier than array as the elements in an array are stored in a
consecutive location. In contrast, in the case of a linked list, the elements are stored in a random
location. The complexity for insertion and deletion of elements from the beginning is O(1) in the
126
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
linked list, while in the case of an array, the complexity would be O(n). If we want to insert or delete
the element in an array, then we need to shift the elements for creating the space. On the other
hand, in the linked list, we do not have to shift the elements. In the linked list, we just need to
update the address of the pointer in the node.
Memory efficient
Its memory consumption is efficient as the size of the linked list can grow or shrink according to our
requirements.
Implementation
Both the stacks and queues can be implemented using a linked list.
The following are the disadvantages of linked list:
Memory usage
The node in a linked list occupies more memory than array as each node occupies two types of
variables, i.e., one is a simple variable, and another is a pointer variable that occupies 4 bytes in the
memory.
Traversal
n s
In a linked list, the traversal is not easy. If we want to access the element in a linked list, we cannot
access the element randomly, but in the case of an array, we can randomly access the element by
tio
index. For example, if we want to access the 3rd node, then we need to traverse all the nodes
Reverse traversing
l i a
before it. So, the time required to access a particular node is large.
c
u
requires more memory to store the back pointer. b
In a linked list, backtracking or reverse traversing is difficult. In a doubly linked list, it is easier but
ul P
Q45. What are the applications of linked list ?
Ans :
a h
The applications of the linked list are given below:
R
With the help of a linked list, the polynomials can be represented as well as we can perform the
operations on the polynomial. We know that polynomial is a collection of terms in which each term
contains coefficient and power. The coefficients and power of each term are stored as node and link
pointer points to the next element in a linked list, so linked list can be used to create, delete and display the
polynomial.
A sparse matrix is used in scientific compu-tation and numerical analysis. So, a linked list is used to
represent the sparse matrix.
The various operations like student’s details, employee’s details or product details can be implemented
using the linked list as the linked list uses the structure data type that can hold different data types.
127
Rahul Publications
B.Sc. II YEAR III SEMESTER
n
tio
structnode *temp = head;
Following are the basic operations supported
while(temp->next != NULL){
by a list.
Insertion: add an element at the beginning
l i c a
temp = temp->next;
of the list.
b }
Pu
temp->next = newNode;
Deletion: delete an element at the beginning
of the list.
ah
Display: displaying complete list.
node.
Search: search an element using given key.
R
Delete: delete an element using given key.
Q46. Explain the process of inserting a new
Traverse to node just before the required
position of new node.
Change next pointers to include new
node in between.
element into the linked list.
structnode *newNode;
Ans : (Dec.-17)
newNode = malloc(sizeof(structnode));
You can add elements to either the beginning, newNode->data = 4;
middle or end of the linked list.
structnode *temp = head;
1. Insert at the beginning for(int i=2; i < position; i++) {
Allocate memory for new node if(temp->next != NULL) {
Store data temp = temp->next;
}
Change next of new node to point to
head }
128
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Q47. How can we delete an element from the struct node* temp = head;
linked list ? while(temp->next->next!=NULL){
Ans : (Dec.-17) temp = temp->next;
You can delete either from the beginning, end }
or from a particular position. temp->next = NULL;
1. Delete from beginning 3. Delete from middle
Point head to the second node Traverse to element before the element
head = head->next; to be deleted
2. Delete from end Change next pointers to exclude the
Traverse to second last element node from the chain
Change its next pointer to null for(int i=2; i< position; i++) {
struct node* temp = head; if(temp->next!=NULL) {
while(temp->next->next!=NULL){ temp = temp->next;
temp = temp->next; }
} }
n s
tio
temp->next = NULL; temp->next = temp->next->next;
3. Delete from middle Q49. How can we search a specific element
Traverse to element before the element
to be deleted
l i c a
in the linked list?
b
Ans : (Dec.-17, Imp.)
Pu
Change next pointers to exclude the
node from the chain You can search an element on a linked list
l
for(int i=2; i< position; i++) {
u
using a loop using the following steps. We are
finding item on a linked list.
ah
if(temp->next!=NULL) {
Make head as the current node.
temp = temp->next;
}
}
R
temp->next = temp->next->next;
Run a loop until the current node is NULL
because the last element points to NULL.
In each iteration, check if the key of the node
is equal to item. If it the key matches the item,
Q48. How can we search a specific element return true otherwise return false.
in the linked list? // Search a node
Ans : (Dec.-17, Imp.) bool searchNode(structNode** head_ref, int
key) {
You can delete either from the beginning, end
or from a particular position. structNode* current = *head_ref;
1. Delete from beginning while (current != NULL) {
Point head to the second node if (current->data == key) returntrue;
head = head->next; current = current->next;
2. Delete from end }
Traverse to second last element returnfalse;
Change its next pointer to null }
129
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Sort Elements of a Linked List
We will use a simple sorting algorithm, Bubble Sort, to sort the elements of a linked list in ascending
order below.
1. Make the head as the current node and create another node index for later use.
2. If head is null, return.
3. Else, run a loop till the last node (i.e. NULL).
4. In each iteration, follow the following step 5-6.
5. Store the next node of current in index.
6. Check if the data of the current node is greater than the next node. If it is greater,
swap current and index.
Check the article on bubble sort for better understanding of its working.
// Sort the linked list
n s
tio
void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;
l i c a
if (head_ref == NULL) {
u b
return;
} else {
ul P
a h
while (current != NULL) {
// index points to the node next to current
R
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
130
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans :
// Linked list operations in C++
#include <stdlib.h>
#include <iostream>
using namespace std;
// Create a node
struct Node {
int data;
struct Node* next;
};
void insertAtBeginning(struct Node** head_ref, int new_data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// insert the data
n s
new_node->data = new_data;
new_node->next = (*head_ref);
c a tio
// Move head to new node
b l i
(*head_ref) = new_node;
}
P u
h ul
// Insert a node after a node
void insertAfter(struct Node* prev_node, int new_data) {
a
R
if (prev_node == NULL) {
cout << “the given previous node cannot be NULL”;
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
// Insert at the end
void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/
new_node->data = new_data;
new_node->next = NULL;
131
Rahul Publications
B.Sc. II YEAR III SEMESTER
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) last = last->next;
last->next = new_node;
return;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
n s
}
// Find the key to be deleted
c a tio
while (temp != NULL && temp->data != key) {
b l i
prev = temp;
temp = temp->next;
P u
}
a h
// If the key is not present ul
R
if (temp == NULL) return;
// Remove the node
prev->next = temp->next;
free(temp);
}
// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
while (current != NULL) {
if (current->data == key) return true;
current = current->next;
}
return false;
}
132
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
l i c a
current = current->next;
u b
}
}
ul P
}
a h
// Print the linked list
R
void printList(struct Node* node) {
while (node != NULL) {
cout << node->data << “ “;
node = node->next;
}
}
// Driver program
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);
133
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
printList(head);
}
2.3.2 Linked List Abstract Data Type
l i c a
b
Q52. Discuss in detail Linked List representation using ADT.
u
Ans :
ul P
Linked List can be defined as collection of objects called nodes that are randomly stored in the
memory.
a h
R
A node contains two fields i.e. data stored at that particular address and the pointer which contains
the address of the next node in the memory.
The last node of the list contains pointer to the null.
134
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
It involves deletion of a node from the beginning of the
tio
list. This is the simplest operation among all. It just need a
few adjustments in the node pointers.
2. Deletion at the end of the list
c a
It involves deleting the last node of the list. The list can
l i
either be empty or full. Different logic is implemented for
u b
the different scenarios.
3. Deletion after specified node
4.
a
Traversingh requires traversing through the list.
In traversing, we simply visit each node of the list at least
Ans :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Linked_list_Stack
{
private:
135
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
void Linked_list_Stack::pop( )
void push( );
{
void print_list( );
void show_working( );
l i c a
if(bottom==NULL)
};
u b cout<<“\n\t *** Error : Stack is empty.
\n”<<endl;
{
ul P
Linked_list_Stack::Linked_list_Stack ( )
else
top=NULL;
a h {
for(l ast_e ntr y= bottom;l ast_entr y-
bottom=NULL;
} R
void Linked_list_Stack::push( )
>next!=NULL;
last_entry=last_entry->next)
second_last_entry=last_entry;
{
if(top==bottom)
int num;
bottom=NULL;
cout<<“\n\t Enter value to push onto
Stack : “; int poped_element=top->data;
136
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
} case 2: pop();
void Linked_list_Stack::print_list( ) break;
{ case 3: print_list( );
print=bottom; break;
while(print!=NULL) }while(1);
}
{
int main( )
cout<<“\t “<<print->data<<endl;
{
print=print->next;
Linked_list_Stack obj;
}
n s
obj.show_working( );
tio
}
return 0;
void Linked_list_Stack::show_working( )
{
l i c
}
a
2.3.3 Liked List variants, Doubly Linked List,
int choice;
b Circular Linked List.
Pu
clrscr( ); Q54. Discuss in short types of Linked Lists.
Linked List as a
ul
cout<<“\n\n********** Implementation of Ans :
ah
The following are the types of linked list:
Stack **********”<<endl;
<endl; R
cout<<“\n1.Push elements to stack”<
137
Rahul Publications
B.Sc. II YEAR III SEMESTER
head
100
We can observe in the above figure that there are three different nodes having address 100, 200
and 300 respectively. The first node contains the address of the next node, i.e., 200, the second
node contains the address of the last node, i.e., 300, and the third node contains the NULL value
in its address part as it does not point to any node. The pointer that holds the address of the initial
node is known as a head pointer.
The linked list, which is shown in the above diagram, is known as a singly linked list as it contains
only a single link. In this list, only forward traversal is possible; we cannot traverse in the backward
direction as it has only one link in the list.
(2)
Doubly linked list
n s
As the name suggests, the doubly linked list contains two pointers. We can define the doubly linked
tio
list as a linear data structure with three parts: the data part and the other two address part. In other
a
words, a doubly linked list is a list that has three parts in a single node, includes one data part, a
c
pointer to its previous node, and a pointer to the next node.
l i
u b
Suppose we have three nodes, and the address of these nodes are 100, 200 and 300, respectively.
The representation of these nodes in a doubly-linked list is shown below:
Null 1
ul P200 100 2 300 200 3 NULL
100
As we can observe in the above figure, the node in a doubly-linked list has two address parts; one
part stores the address of the next while the other part of the node stores the previous node’s
address. The initial node in the doubly linked list has the NULL value in the address part, which
provides the address of the previous node.
(3) Circular linked list
A circular linked list is a variation of a singly linked list. The only difference between the singly
linked list and a circular linked list is that the last node does not point to any node in a singly linked
list, so its link part contains a NULL value. On the other hand, the circular linked list is a list in which the last
node connects to the first node, so the link part of the last node holds the first node’s address. The circular
linked list has no starting and ending node.
A circular linked list is a sequence of elements in which each node has a link to the next node, and
the last node is having a link to the first node. The representation of the circular linked list will be similar to
the singly linked list, as shown below:
138
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
c a tio
b l i
The above figure shows the representation of the doubly circular linked list in which the last node is
P u
attached to the first node and thus creates a circle. It is a doubly linked list also because each node holds
the address of the previous node also. The main difference between the doubly linked list and doubly
ul
circular linked list is that the doubly circular linked list does not contain the NULL value in the previous
a h
field of the node. As the doubly circular linked contains three parts, i.e., two address parts and one data
part so its representation is similar to the doubly linked list.
Ans :
list. R
Q55. Discuss in detail about Doubly Linked List. Explain the basic operations of Doubly linked
(Dec.-19)
Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous
as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts:
node data, pointer to the next node in sequence (next pointer) , pointer to the previous node (previous
pointer). A sample node in a doubly linked list is shown in the figure.
Head
Node
A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown
in the following image.
139
Rahul Publications
B.Sc. II YEAR III SEMESTER
tio
list
5
6
Deletion at the end
Deletion of the node having given data
l i a
Removing the node from end of the list.
c
Removing the node which is present just after
Pu
7 Searching Comparing each node data with the item to
ah
null.
8 Traversing Visiting each node of the list at least once in
R
Insertion in doubly linked list at beginning
order to perform some specific operation like
searching, sorting, display, etc.
Algorithm
Step 1: IF ptr = NULL
Write OVERFLOW
Go to Step 9
[END OF IF]
Step 2: SET NEW_NODE = ptr
Step 3: SET ptr = ptr -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> PREV = NULL
Step 6: SET NEW_NODE -> NEXT = START
Step 7: SET head -> PREV = NEW_NODE
Step 8: SET head = NEW_NODE
Step 9: EXIT
140
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
c a tio
Go to Step 15
b l i
Step 2:
[END OF IF]
SET NEW_NODE = PTR
P u
Step 3:
Step 4:
h ul
SET PTR = PTR -> NEXT
SET NEW_NODE -> DATA = VAL
a
Step 5:
Step 6:
Step 7:
R
SET TEMP = START
SET I = 0
REPEAT 8 to 10 until I<=”” li=””>
Step 8: SET TEMP = TEMP -> NEXT
Step 9: IF TEMP = NULL
Step 10: WRITE “LESS THAN DESIRED NO. OF ELEMENTS”
GOTO STEP 15
[END OF IF]
[END OF LOOP]
Step 11: SET NEW_NODE -> NEXT = TEMP -> NEXT
Step 12: SET NEW_NODE -> PREV = TEMP
Step 13 : SET TEMP -> NEXT = NEW_NODE
Step 14: SET TEMP -> NEXT -> PREV = NEW_NODE
Step 15: EXIT
141
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
#include<iostream>
n s
tio
usingnamespace std;
structNode{
int data;
l i c a
structNode*prev;
u b
};
structNode*next;
ul P
a h
structNode* head = NULL;
void insert(int newdata){
R
structNode* newnode =(structNode*) malloc(sizeof(structNode));
newnode->data = newdata;
newnode->prev = NULL;
newnode->next= head;
if(head != NULL)
head->prev = newnode ;
head = newnode;
}
void display(){
structNode* ptr;
ptr = head;
while(ptr != NULL){
cout<< ptr->data <<“ “;
142
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
ptr = ptr->next;
int main(){
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
display();
n s
tio
return0;
Output
l i c a
The doubly linked list is: 9 2 7 1 3
u b
ul P
Q57. Discuss In detail deletion, search in doubly linked list.
Ans :
a h (Dec.-19)
R
Operations on Circular Singly linked list
Deletion at beginning
Algorithm
WRITE UNDERFLOW
GOTO STEP 6
STEP 6: EXIT
143
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL
l i c a
Step 4: SET TEMP = TEMP->NEXT
[END OF LOOP]
u b
Step 5:
ul P
SET TEMP ->PREV-> NEXT = NULL
h
Step 6: FREE TEMP
Step 7: EXIT
R a
144
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Go to Step 9
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: Repeat Step 4 while TEMP -> DATA != ITEM
Step 4: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 5: SET PTR = TEMP -> NEXT
Step 6: SET TEMP -> NEXT = PTR -> NEXT
Step 7: SET PTR -> NEXT -> PREV = TEMP
Step 8: FREE PTR
Step 9: EXIT
n s
c a tio
b l i
P u
h ul
Searching for a specific node in Doubly Linked List
Algorithm
a
Step 1:
R
IF HEAD == NULL
WRITE “UNDERFLOW”
GOTO STEP 8
[END OF IF]
Step 2: Set PTR = HEAD
Step 3: Set i = 0
Step 4: Repeat step 5 to 7 while PTR != NULL
Step 5: IF PTR ’! data = item
return i
[END OF IF]
Step 6: i=i+1
Step 7: PTR = PTR ’! next
Step 8: Exit
145
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
#include<iostream>
usingnamespace std;
structNode{
int data;
structNode*prev;
structNode*next;
};
structNode* head = NULL;
void insert(int newdata){
structNode* newnode =(structNode*) malloc(sizeof(structNode));
newnode->data = newdata;
newnode->prev = NULL;
n s
newnode->next= head;
if(head != NULL)
c a tio
head->prev = newnode ;
b l i
head = newnode;
P u
ul
}
void display(){
a
structNode* ptr;
h
ptr = head;
R
while(ptr != NULL){
cout<< ptr->data <<“ “;
ptr = ptr->next;
}
}
int main(){
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<“The doubly linked list is: “;
146
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
display();
return0;
}
Output
The doubly linked list is: 9 2 7 1 3
Q59. Discuss In detail about Circular Single Linked List.
Ans :
In a circular Singly linked list, the last node of the list contains a pointer to the first node of the list.
We can have circular singly linked list as well as circular doubly linked list.
We traverse a circular singly linked list until we reach the same node where we started. The circular
singly liked list has no beginning and no ending. There is no null value present in the next part of any of
the nodes.
The following image shows a circular singly linked list.
n s
c a tio
b l i
P u
a h ul
Operations on Circular Singly Linked List
Sl. No.
1.
R
Operation
Insertion at beginning
Description
Adding a node into circular singly linked list at the beginning.
2. Insertion at the end Adding a node into circular singly linked list at the end.
Deletion and Traversing
2 Deletion at the end Removing the node from circular singly linked list at the end.
3 Searching Compare each element of the node with the given item and
return the location at which the item is present in the list
otherwise return null.
4 Traversing Visiting each element of the list at least once in order to perform
some specific operation.
147
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
b l i
P u
a h ul
R
148
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
c a tio
b l i
P u
h ul
Deletion in circular singly linked list at beginning
a
Algorithm
Step 1: R
IF HEAD = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Step 4 while PTR ’! NEXT != HEAD
Step 4: SET PTR = PTR ’! next
[END OF LOOP]
Step 5: SET PTR ’! NEXT = HEAD ’! NEXT
Step 6: FREE HEAD
Step 7: SET HEAD = PTR ’! NEXT
Step 8: EXIT
149
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
Step 2: SET PTR = HEAD
P u
ul
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
Step 4:
h
SET PREPTR = PTR
a
Step 5:
Step 6:
R
SET PTR = PTR -> NEXT
[END OF LOOP]
SET PREPTR -> NEXT = HEAD
Step 7: FREE PTR
Step 8: EXIT
150
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans ;
#include<iostream>
usingnamespace std;
structNode{
int data;
structNode*next;
};
structNode* head = NULL;
void insert(int newdata){
structNode*newnode =(structNode*)malloc(sizeof(structNode));
structNode*ptr = head;
newnode->data = newdata;
newnode->next= head;
n s
if(head!= NULL){
while(ptr->next!= head)
c a tio
ptr = ptr->next;
b l i
ptr->next= newnode;
P u
ul
} else
newnode->next= newnode;
head = newnode;
a h
}
void display(){
R
structNode* ptr;
ptr = head;
do{
cout<<ptr->data <<“ “;
ptr = ptr->next;
}while(ptr != head);
}
int main(){
insert(3);
insert(1);
insert(7);
151
Rahul Publications
B.Sc. II YEAR III SEMESTER
insert(2);
insert(9);
cout<<“The circular linked list is: “;
display();
return0;
}
Output
The circular linked list is: 9 2 7 1 3
Q61. Discuss in detail about Circular Doubly linked list.
Ans :
Circular doubly linked list is a more complexed type of data structure in which a node contain
pointers to its previous node as well as the next node. Circular doubly linked list doesn’t contain NULL in
any of the node. The last node of the list contains the address of the first node of the list. The first node of
the list also contain address of the last node in its previous pointer.
A circular doubly linked list is shown in the following figure.
n s
c a tio
b l i
P u
a h ul
Operations on circular doubly linked list
R
There are various operations which can be performed on circular doubly linked list. The node
structure of a circular doubly linked list is similar to doubly linked list. However, the operations on circular
doubly linked list is described in the following table.
Sl. No. Operation Description
1 Insertion at beginning Adding a node in circular doubly linked list at the beginning.
2 Insertion at end Adding a node in circular doubly linked list at the end.
3 Deletion at beginning Removing a node in circular doubly linked list from beginning.
4 Deletion at end Removing a node in circular doubly linked list at the end.
Insertion in circular doubly linked list at beginning
Algorithm
Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 13
[END OF IF]
152
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
c a tio
b l i
P u
a h ul
Insertion in circular doubly linked list at end
Algorithm
R
Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = HEAD
Step 6: SET TEMP = HEAD
Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 8: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 9: SET TEMP -> NEXT = NEW_NODE
Step 10: SET NEW_NODE -> PREV = TEMP
Step 11: SET HEAD -> PREV = NEW_NODE
Step 12: EXIT
153
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
Write UNDERFLOW
Go to Step 8
[END OF IF]
l i c a
Step 2: SET TEMP = HEAD
u b
Step 3:
Step 4:
ul P
Repeat Step 4 while TEMP -> NEXT != HEAD
SET TEMP = TEMP -> NEXT
h
[END OF LOOP]
a
Step 5:
Step 6:
Step 7:
R
SET TEMP -> NEXT = HEAD -> NEXT
SET HEAD -> NEXT -> PREV = TEMP
FREE HEAD
Step 8: SET HEAD = TEMP -> NEXT
154
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Pu
comparison
Definition A single linked list is a list of nodes A doubly linked list is also a collection of
ul
in which node has two parts, the first
part is the data part, and the next
nodes in which node has three fields, the
first field is the pointer containing the address
ah
part is the pointer pointing to the next of the previous node, the second is the data
node in the sequence of nodes. field, and the third is the pointer containing
Access
RThe singly linked list can be traversed
only in the forward direction.
the address of the next node.
List pointer It requires only one list pointer variable, It requires two list pointer variables, head
i.e., the head pointer pointing to the and last. The head pointer points to the first
node. node, and the last pointer points to the
last node of the list.
Memory space It utilizes less memory space. It utilizes more memory space.
Efficiency It is less efficient as compared to a It is more efficient.
doubly-linked list.
155
Rahul Publications
B.Sc. II YEAR III SEMESTER
2.3.4 Representation of Sparse Matrix In above example matrix, there are only 6
using Linked List non-zero elements ( those are 9, 8, 4, 2, 5 and 2)
and matrix size is 5 × 6. We represent this matrix
Q63. What is Sparse Matrix?
as shown in the above image. Here the first row in
Ans : the right side table is filled with values 5, 6 & 6
In computer programming, a matrix can be which indicates that it is a sparse matrix with 5 rows,
defined with a 2-dimensional array. Any array with 6 columns & 6 non-zero values. The second row is
‘m’ columns and ‘n’ rows represent a m X n matrix. filled with 0, 4, & 9 which indicates the non-zero
There may be a situation in which a matrix contains value 9 is at the 0th-row 4th column in the Sparse
more number of ZERO values than NON-ZERO matrix. In the same way, the remaining non-zero
values. Such matrix is known as sparse matrix. values also follow a similar pattern.
When a sparse matrix is represented with a #include<iostream>
2-dimensional array, we waste a lot of space to
represent that matrix. For example, consider a using namespace std;
matrix of size 100 × 100 containing only 10 non- int main()
zero elements. In this matrix, only 10 spaces are
{
filled with non-zero values and remaining spaces of
the matrix are filled with zero. That means, totally // sparse matrix of class 5x6 with 6 non-zero values
we allocate 100 × 100 × 2 = 20000 bytes of space
to store this integer matrix. And to access these 10
n s
int sparseMatrix[5][6] =
tio
non-zero elements we have to make scanning for {
10000 times. To make it simple we use the following
sparse matrix representation.Sparse Matrix
Representations
l i c a{0 , 0 , 0 , 0 , 9, 0 },
{0 , 8 , 0 , 0 , 0, 0 },
b
Pu
A sparse matrix can be represented by using {4 , 0 , 0 , 2 , 0, 0 },
TWO representations, those are as follows...
{0 , 0 , 0 , 0 , 0, 5 },
1.
2.
u
Linked Representationl
Triplet Representation (Array Representation)
{0 , 0 , 2 , 0 , 0, 0 }
ah
1. Triplet Representation (Array Represen- };
tation)
R
In this representation, we consider only non-
zero values along with their row and column index
values. In this representation, the 0th row stores the
//Finding total non-zero values in the sparse
matrix
int size = 0;
total number of rows, total number of columns and for (int row = 0; row < 5; row++)
the total number of non-zero values in the sparse for (int column = 0; column < 6;
matrix. column++)
For example, consider a matrix of size 5 X 6
containing 6 number of non-zero values. This matrix if (sparseMatrix[row][column] != 0)
can be represented as shown in the image... size++;
Rows Colums Values // Defining result Matrix
5 6 6
int resultMatrix[3][size];
0 0 0 0 9 0 0 4 9
0 8 0 0 0 0
1 1 8 // Generating result matrix
4 0 0 2 0 0 2 0 4
int k = 0;
0 0 0 0 0 5 2 3 2
0 0 2 0 0 0 2 3 2 for (int row = 0; row < 5; row++)
3 5 5
for (int column = 0; column < 6; column
4 2 2
++)
156
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
if (sparseMatrix[row][column] != 0)
{
resultMatrix[0][k] = row;
resultMatrix[1][k] = column;
resultMatrix[2][k] = sparseMatrix[row][column];
k++;
}
// Displaying result matrix
cout<<“Triplet Representation : “<<endl;
for (int row=0; row<3; row++)
{
for (int column = 0; column<size; column++)
n s
tio
cout<<resultMatrix[row][column]<<“ “;
}
cout<<endl;
l i c a
return 0;
u b
}
Output
ul P
a h
R
157
Rahul Publications
B.Sc. II YEAR III SEMESTER
Linked Representation
In linked representation, we use a linked list data structure to represent a sparse matrix. In this
linked list, we use two different nodes namely header node and element node. Header node consists
of three fields and element node consists of five fields as shown in the image...
Consider the above same sparse matrix used in the Triplet representation. This sparse matrix can be
represented using linked representation as shown in the below image...
n s
c a tio
b l i
P u
a h ul
R
In the above representation, H0, H1,..., H5 indicates the header nodes which are used to represent
indexes. Remaining nodes are used to represent non-zero elements in the matrix, except the very first
node which is used to represent abstract information of the sparse matrix (i.e., It is a matrix of 5 X 6 with
6 non-zero elements).
In this representation, in each row and column, the last node right field points to its respective
header node.
2.3.5 Linked Stack , Linked Queue
Q64. What is Linked Stack ? Explain in detail.
(OR)
Explain the implementation of stack using linked list representation.
Ans :
The major problem with the stack implemented using an array is, it works only for a fixed number
of data values. That means the amount of data must be specified at the beginning of the implementation
158
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
itself. Stack implemented using an array is not Push(value) - Inserting an element into the
suitable, when we don’t know the size of data which Stack
we are going to use. A stack data structure can be
We can use the following steps to insert a new
implemented by using a linked list data structure.
node into the stack...
The stack implemented using linked list can work
for an unlimited number of values. That means, Step 1: Create a newNode with given value.
stack implemented using linked list works for the
Step 2: Check whether stack is Empty (top ==
variable size of data. So, there is no need to fix the
NULL)
size at the beginning of the implementation. The
Stack implemented using linked list can organize as Step 3: If it is Empty, then set newNode’™
many data values as we want. next = NULL.
In linked list implementation of a stack, every new Step 4: If it is Not Empty, then set new Node’™
element is inserted as ‘top’ element. That means next = top.
every newly inserted element is pointed by ‘top’.
Step 5: Finally, set top = newNode.
Whenever we want to remove an element from the
stack, simply remove the node which is pointed by pop() - Deleting an Element from a Stack
‘top’ by moving ‘top’ to its previous node in the
We can use the following steps to delete a
list. The next field of the first element must be
always NULL.
node from the stack...
n s
tio
Step 1: Check whether stack is Empty (top
Example
== NULL).
l i c a
Step 2: If it is Empty, then display ”Stack is
Empty!!! D eletion is not pos-
Pu
Step 3: If it is Not Empty, then define a Node
R ah
In the above example, the last inserted node
is 99 and the first inserted node is 25. The order of
elements inserted is 25, 32,50 and 99.
Step 5: Finally, delete ‘temp’. (free(temp)).
display() - Displaying stack of
elements
We can use the following steps to display the
Stack Operations using Linked List
elements (nodes) of a stack...
To implement a stack using a linked list, we
need to set the following things before implementing Step 1: Check whether stack is Empty(top
actual operations. == NULL).
Step 1: Include all the header files which are Step 2: If it is Empty, then display ‘Stack is
used in the program. And declare all Empty!!!’ and terminate the function.
the user defined functions.
Step 3: If it is Not Empty, then define a Node
Step 2: Define a ‘Node’ structure with two pointer ’temp’ and initialize with top.
members data and next.
Step 3: Define a Node pointer ‘top’ and set it Step 4: Display ‘temp ’! data —>’ and move
to NULL. it to the next node. Repeat the same
until temp reaches to the first node in
Step 4: Implement the main method by
the stack. (temp ’! next != NULL).
displaying Menu with list of operations and
make suitable function calls in the main Step 5: Finally! Display ‘temp ’! data —
method. > NULL’.
159
Rahul Publications
B.Sc. II YEAR III SEMESTER
Q65. Write a C++ program to implement stack using linked list representation.
Ans :
#include<iostream>
usingnamespace std;
structNode{
int data;
structNode*next;
};
structNode* top = NULL;
void push(int val){
structNode* newnode =(structNode*) malloc(sizeof(structNode));
newnode->data = val;
newnode->next= top;
}
top = newnode;
n s
void pop(){
if(top==NULL)
c a tio
cout<<“Stack Underflow”<<endl;
b l i
else{
P u
cout<<“The popped element is “<< top->data <<endl;
}
top = top->next;
a h ul
}
void display(){ R
structNode* ptr;
if(top==NULL)
cout<<“stack is empty”;
else{
ptr = top;
cout<<“Stack elements are: “;
while(ptr != NULL){
cout<< ptr->data <<“ “;
ptr = ptr->next;
}
}
cout<<endl;
}
160
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
a
Enter choice: 3
c tio
The popped element is 7
case2:{
l i
Stack elements are:8 6 2
b
pop();
break;
P u Enter choice: 5
Invalid Choice
}
case3:{
ah ul Enter choice: 4
Exit
}
break;R
display();
Q66. Explain the implementation of queue
Ans :
using linked list representation.
case4:{
The major problem with the queue
cout<<“Exit”<<endl; implemented using an array is, It will work for an
break; only fixed number of data values. That means, the
amount of data must be specified at the beginning
} itself. Queue using an array is not suitable when we
default:{ don’t know the size of data which we are going to
cout<<“Invalid Choice”<<endl; use. A queue data structure can be implemented
using a linked list data structure. The queue which
} is implemented using a linked list can work for an
} unlimited number of values. That means, queue
using linked list can work for the variable size of
}while(ch!=4);
data (No need to fix the size at the beginning of the
return0; implementation). The Queue implemented using
} linked list can organize as many data values as we
want.
161
Rahul Publications
B.Sc. II YEAR III SEMESTER
In linked list implementation of a queue, the last inserted node is always pointed by ‘rear’ and the
first node is always pointed by ‘front’.
Example
In above example, the last inserted node is 50 and it is pointed by ‘rear’ and the first inserted node
is 10 and it is pointed by ‘front’. The order of elements inserted is 10, 15, 22 and 50.
Operations
To implement queue using 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.
n s
Step 3 - Define two Node pointers ‘front’ and ‘rear’ and set both to NULL.
tio
Step 4 - Implement the main method by displaying Menu of list of operations and make suitable
l i a
function calls in the main method to perform user selected operation.
c
u b
We can use the following steps to insert a new node into the queue...
Step 1 - Create a newNode with given value and set ‘newNode ’™ next’ to NULL.
ul P
Step 2 - Check whether queue is Empty (rear == NULL)
Step 3 - If it is Empty then, set front = newNode and rear = newNode.
a h
Step 4 - If it is Not Empty then, set rear ’™ next = newNode and rear = newNode.
R
deQueue() - Deleting an Element from Queue
We can use the following steps to delete a node from the queue...
Step 1 - Check whether queue is Empty (front == NULL).
Step 2 - If it is Empty, then display ”Queue is Empty!!! Deletion is not possible!!!” and
terminate from the function
Step 3 - If it is Not Empty then, define a Node pointer ‘temp’ and set it to ‘front’.
Step 4 - Then set ‘front = front ’! next’ and delete ‘temp’ (free(temp)).
display() - Displaying the elements of Queue
We can use the following steps bto display the elements (nodes) of a queue...
Step 1 - Check whether queue is Empty (front == NULL).
Step 2 - If it is Empty then, display ’Queue is Empty!!!’ and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer ’temp’ and initialize with front.
Step 4 - Display ‘temp ’! data —>’ and move it to the next node. Repeat the same until ‘temp’
reaches to ‘rear’ (temp ’! next != NULL).
Step 5 - Finally! Display ‘temp ’! data —> NULL’.
162
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Q67. Write a C++ program to implement queue using linked list representation
Ans :
#include<iostream>
usingnamespace std;
struct node {
int data;
struct node *next;
};
struct node* front = NULL;
struct node* rear = NULL;
struct node* temp;
voidInsert(){
int val;
cout<<“Insert the element in queue : “<<endl;
cin>>val;
n s
if(rear == NULL){
rear =(struct node *)malloc(sizeof(struct node));
c a tio
rear->next= NULL;
b l i
rear->data = val;
front = rear;
P u
}else{
h ul
temp=(struct node *)malloc(sizeof(struct node));
a
R
rear->next= temp;
temp->data = val;
temp->next= NULL;
rear = temp;
}
}
voidDelete(){
temp = front;
if(front == NULL){
cout<<“Underflow”<<endl;
return;
}
else
if(temp->next!= NULL){
temp = temp->next;
163
Rahul Publications
B.Sc. II YEAR III SEMESTER
while(temp != NULL){
ul P 3)
4)
Display all the elements of queue
Exit
ah
cout<<temp->data<<“ “;
Enter your choice : 1
temp = temp->next;
}
cout<<endl;
R Insert the element in queue : 4
Enter your choice : 1
Insert the element in queue : 3
}
Enter your choice : 1
int main(){
Insert the element in queue : 5
int ch;
Enter your choice : 2
cout<<“1) Insert element to queue”<<endl;
Element deleted from queue is : 4
cout<<“2) Delete element from
queue”<<endl; Enter your choice : 3
cout<<“3) Display all the elements of Queue elements are : 3 5
queue”<<endl;
Enter your choice : 7
cout<<“4) Exit”<<endl;
Invalid choice
do{
Enter your choice : 4
cout<<“Enter your choice : “<<endl;
Exit
cin>>ch;
164
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
Ans :
The process in which a function calls itself is known as recursion and the corresponding function is
called the recursive function. The popular example to understand the recursion is factorial function.
Factorial function
f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil discuss what is base
condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
Factorial function:f(n) = n*f(n–1)
Lets say we want to find out the factorial of 5 which means n = 5.
f(5)=5*f(5–1)=5*f(4)
n s
tio
5*4*f(4–1)= 20*f(3)
l
20*3*f(3-1)=60*f(2)
i c a
u b
ul P 60*2*f(2-1) = 120*f(1)
a h 120*1*f(1-1) = 120*f(0)
R
#include<iostream>
usingnamespace std;
120*1=120
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
if (n <= 1)
return1;
else
return n*f(n-1);
}
165
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
return n * fact(n -1);
tio
else
Less number code lines are used in the
recursion program and hence the code looks return1;
shorter and cleaner.
Recursion is easy to approach to solve the
l i c a}
Pu
algorithms like graph and tree. Enter an positive integer: 6
complexity.
ul
Recursion helps to reduce the time Factorial of 6 = 720
ah
4. Write a c++ program to reverse a
It helps to reduce unnecessary calling of the number using recursion.
function.
R
It helps to solve the stack evolutions and
prefix, infix, postfix evaluation.
Recursion is the best method to define objects
Ans :
#include <iostream.h>
using namespace std;
that have repeated structural forms.
int reverseNumber(int n) {
Disadvantages
static temp,sum;
It consumes a lot of stack space
if(n>0){
It takes more time to process the program
temp = n%10;
If an error is accrued in the program, it is
sum=sum*10+ temp;
difficult to debug the error in comparison to
the iterative program. reverseNumber(n/10);
3. Write a C++ program to find factorial }
of given number using recursion. else
Ans : {
#include <iostream> returnsum;
using namespace std; }
166
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
}
int main()
{
int n,reverse;
cout<<“Enter number”;
cin >> n;
reverse = reverseNumber(n);
cout <<“Reverse of number is”<< reverse;
return0;
}
Output
Enter number : 3456
Reverse of number is : 6543
5. Define Recurrence.
n s
tio
Ans :
l
that something has been repeated. It may even be a variable.
i a
Recurrence means, the number of times, that a function has recused. It may also mean, simply,
c
u b
A recurrence is a well-defined mathematical function where the function being defined is applied
within its own definition. The mathematical function factorial of n can also be defined recursively as n! =
ul P
n × (n - 1)!, where 1! = 1 Fibonacci sequence as an example. The Fibonacci sequence is the sequence of
numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... The first two numbers of the sequence are both 1, whereas
a h
each succeeding number is the sum of the preceding two numbers (we arrived at 55 as the 10th number;
it is the sum of 21 and 34, the eighth and ninth numbers).
6.
Ans : R
What is recursive function?
Recursive Functions is the process of defining something in terms of itself. It is a function that calls
itself again in the body of the function.
A function fact ( ), that computes the factorial of an integer ‘N’ ,which is the product of all whole
numbers from 1 to N.
When fact ( ) is called with an argument of 1 (or) 0, the function returns 1. Otherwise, it returns the
product of n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) = 5* fact (4)
= 5*4*3* fact (3)
= 5*4*3*2* fact (2)
= 5*4*3*2*1 fact (1)
= 5*4*3*2*1
= 120.
167
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
On the basis Recursion Iteration
Basic Recursion is the process of calling In iteration, there is a repeated execution of the
a function itself within its own code. set of instructions. In Iteration, loops are used
to execute the set of instructions repetitively until
the condition is false.
Syntax There is a termination condition is The format of iteration includes initialization,
specified. condition, and increment/decrement of a variable.
Termination The termination condition is defined Here, the termination condition is defined in the
within the recursive function. definition of the loop.
Code size The code size in recursion is smaller The code size in iteration is larger than the code
than the code size in iteration. size in recursion.
Infinite If the recursive function does not Iteration will be infinite, if the control condition of
meet to a termination condition, it the iteration statement never becomes false. On
leads to an infinite recursion. There infinite loop, it repeatedly used CPU cycles.
is a chance of system crash in
infinite recursion.
n s
tio
Applied It is always applied to functions. It is applied to loops.
Speed
Usage
It is slower than iteration.
Recursion is generally used where
i a
It is faster than recursion.
c
It is used when we have to balance the time
l
b
there is no issue of time complexity, complexity against a large code size.
Pu
and code size requires being small.
Time It has high time complexity. The time complexity in iteration is relatively lower.
complexity
ah
Stack It has to update and maintain the There is no utilization of stack.
stack.
Memory
Overhead
R It uses more memory as compared
to iteration.
There is an extensive overhead due
It uses less memory as compared to recursion.
168
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first,
exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following
diagram given below tries to explain queue representation as data structure:
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.
For the sake of simplicity, we shall implement queues using one-dimensional array.
A queue in the data structure can be considered similar to the queue in the real-world. A queue is
a data structure in which whatever comes first will go out first. It follows the FIFO (First-In-First-Out)
policy. In Queue, the insertion is done from one end known as the rear end or the tail of the queue,
n s
whereas the deletion is done from another end known as the front end or the head of the queue. In other
words, it can be defined as a list or a collection with a constraint that the insertion can be performed at one
c a tio
end called as the rear end or tail of the queue and deletion is performed on another end called as the
b l i
P u
a h ul
9.
Ans :
R
List out the basic operation of a Queue.
169
Rahul Publications
B.Sc. II YEAR III SEMESTER
tio
In deque, the insertion and deletion operation Characteristics of a Priority queue
can be performed from one side. The stack follows
the LIFO rule in which both the insertion and
deletion can be performed only from one end;
l i a
Every element in a priority queue has some
c
priority associated with it.
therefore, we conclude that dequeue can be
considered as a stack.
u b
An element with the higher priority will be
deleted before the deletion of the lesser
ul P
In deque, the insertion can be performed on
one end, and the deletion can be done on another
priority.
If two elements in a priority queue have the
a h
end. The queue follows the FIFO rule in which the
same priority, they will be arranged using the
FIFO principle.
R
element is inserted on one end and deleted from
another end. Therefore, we conclude that the deque
can also be considered as the queue.
12.
Ans :
List out the applications of Queues.
170
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
4. Queue are used to maintain the play list in media players in order to add and remove the songs
from the play-list.
5. Queues are used in operating systems for handling interrupts.
13. What are the differences between stack and Queue.
Ans :
Basis for Stack Queue
comparison
Principle It follows the principle LIFO (Last It follows the principle FIFO (First In -
In-First Out), which implies that the First Out), which implies that the
element which is inserted last would element which is added first would
be the first one to be deleted. be the first element to be removed
from the list.
Structure It has only one end from which both It has two ends, i.e., front and rear end.
the insertion and deletion take place, The front end is used for the deletion
and that end is known as a top.
s
while the rear end is used for the insertion.
n
tio
Number of It contains only one pointer known It contains two pointers front and rear
pointers as a top pointer. The top pointer holds pointer. The front pointer holds the
used the address of the last inserted or the
topmost element of the stack.
l i c aaddress of the first element, whereas
the rear pointer holds the address of
u
It performs mainly two operations,
enqueue and dequeue. The enqueue
ah
element in a list while the pop oper- operation performs the insertion of
ation removes the element from the the elements in a queue while
171
Rahul Publications
B.Sc. II YEAR III SEMESTER
14. What are the differences between linear queue and circular queue.
Ans :
Basis of comparison Linear Queue Circular Queue
Meaning The linear queue is a type of linear The circular queue is also a
data structure that contains the linear data structure in which
elements in a sequential manner. the last element of the Queue
is connected to the first
element, thus creating a circle.
Insertion and Deletion In linear queue, insertion is done In circular queue, the insertion
from the rear end, and deletion is and deletion can take place
done from the front end. from any end.
Memory space The memory space occupied by the It requires less memory as
linear queue is more than the compared to linear queue.
circular queue.
Memory utilization The usage of memory is inefficient. The memory can be more
n s
efficiently utilized.
tio
Order of execution It follows the FIFO principle in order It has no specific order for
to perform the tasks. execution.
h
that each element links to its next element in the sequence. Each element in a linked list is called “Node”.
a
R
These elements are linked to each other by providing one additional information along with an
element, i.e., the address of the next element. The variable that stores the address of the next element is
known as a pointer. Therefore, we conclude that the linked list contains two parts, i.e., the first one is the
data element, and the other is the pointer.
A linked list can also be defined as the collection of the nodes in which one node is connected to
another node, and node consists of two parts, i.e., one is the data part and the second one is the address
part, as shown in the below figure:
In the above figure, we can observe that each node contains the data and the address of the next
node. The last node of the linked list contains the NULL value in the address part.
172
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
A linked-list is a sequence of data structures which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another
link. Linked list the second most used data structure after array. Following are important terms to understand
the concepts of Linked List.
Link: Each Link of a linked list can store a data called an element.
Next: Each Link of a linked list contain a link to next link called Next.
LinkedList: A LinkedList contains the connection link to the first Link called First.
Linked List Representation
n s
LinkedList contains an link element called first.
c tio
As per above shown illustration, following are the important points to be considered.
a
b l i
Each Link carries a data field(s) and a Link Field called next.
u
Each Link is linked with its next link using its next link.
P
ul
Last Link carries a Link as null to mark the end of the list.
16.
h
What are the advantges of a linked list.
a
Ans :
R
The following are the advantages of using a linked list over an array:
Dynamic data structure
The size of the linked list is not fixed as it can vary according to our requirements.
Insertion and Deletion
Insertion and deletion in linked list are easier than array as the elements in an array are stored in a
consecutive location. In contrast, in the case of a linked list, the elements are stored in a random
location. The complexity for insertion and deletion of elements from the beginning is O(1) in the
linked list, while in the case of an array, the complexity would be O(n). If we want to insert or delete
the element in an array, then we need to shift the elements for creating the space. On the other
hand, in the linked list, we do not have to shift the elements. In the linked list, we just need to
update the address of the pointer in the node.
Memory efficient
Its memory consumption is efficient as the size of the linked list can grow or shrink according to our
requirements.
173
Rahul Publications
B.Sc. II YEAR III SEMESTER
Implementation
Both the stacks and queues can be implemented using a linked list.
The following are the disadvantages of linked list:
Memory usage
The node in a linked list occupies more memory than array as each node occupies two types of
variables, i.e., one is a simple variable, and another is a pointer variable that occupies 4 bytes in the
memory.
Traversal
In a linked list, the traversal is not easy. If we want to access the element in a linked list, we cannot
access the element randomly, but in the case of an array, we can randomly access the element by
index. For example, if we want to access the 3rd node, then we need to traverse all the nodes
before it. So, the time required to access a particular node is large.
Reverse traversing
17. Explain the insertion of a node in single linked list with example.
c a tio
Ans :
b l i
P u
It is the commonly used linked list in programs. If we are talking about the linked list, it means it is
a singly linked list. The singly linked list is a data structure that contains two parts, i.e., one is the data part,
ul
and the other one is the address part, which contains the address of the next or the successor node. The
address part in a node is also known as a pointer.
a h
Suppose we have three nodes, and the addresses of these three nodes are 100, 200 and 300
R
respectively. The representation of three nodes as a linked list is shown in the below figure:
We can observe in the above figure that there are three different nodes having address 100, 200
and 300 respectively. The first node contains the address of the next node, i.e., 200, the second
node contains the address of the last node, i.e., 300, and the third node contains the NULL value
in its address part as it does not point to any node. The pointer that holds the address of the initial
node is known as a head pointer.
The linked list, which is shown in the above diagram, is known as a singly linked list as it contains
only a single link. In this list, only forward traversal is possible; we cannot traverse in the backward
direction as it has only one link in the list.
174
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
18. What are the differences between single linked list and doubly linked list.
Ans :
Basis of Singly linked list Doubly linked list
comparison
Definition A single linked list is a list of nodes A doubly linked list is also a collection of
in which node has two parts, the first nodes in which node has three fields, the
part is the data part, and the next first field is the pointer containing the address
part is the pointer pointing to the next of the previous node, the second is the data
node in the sequence of nodes. field, and the third is the pointer containing
the address of the next node.
Access The singly linked list can be traversed The doubly linked list can be accessed in
only in the forward direction. both directions.
List pointer It requires only one list pointer variable, It requires two list pointer variables, head
i.e., the head pointer pointing to the and last. The head pointer points to the first
node. node, and the last pointer points to the
last node of the list.
c tio
It is more efficient.
a
Implementation It can be implemented on the stack.
Pu
Complexity In a singly linked list, the time In a doubly-linked list, the time
ul
complexity for inserting and
deleting an element from the
complexity for inserting and deleting
an element is O(1).
ah
list is O(n).
Ans : R
Algorithm for calculating X to the Power of Y i.e XY :
Step 1: Start
Step 7: Stop
175
Rahul Publications
B.Sc. II YEAR III SEMESTER
20. Why linked list is called dynamic data structure? What are the advantages of using
linked list over array.
Ans :
Dynamic Data Structure is that kind of data structure that changes its size during runtime. The
values store in the data structure can be changed easily either it be static or dynamic data structure. But
the dynamic data are designed in such a way that both the data and the size of the data structure can be
easily changed at the runtime.
The main use case for which the Dynamic Data Structures are defined is to easily facilitate the
change in the size of the data structure at the runtime without hindering the other operations that are
associated with that data structure before increasing or decreasing the size of the data structure.
Some of the major examples of dynamic data structures are:
Singly Linked List
Doubly Linked List
Vector
Stack
Queue
n s
tio
Tree
Advantages of using linked list over arrays
l i c a
The principal benefit of a linked list over a conventional array is that the list elements can be easily
inserted or removed without reallocation or reorganization of the entire structure because the data items
more.
u b
need not be stored contiguously in memory or on disk, while restructuring an array at run-time is a much
21.
Ans :
ul P
Describe execution of recursive calls with example.
a h
A recursive call is a command within a subroutine or function that tells the program to run the
R
same subroutine again. The repeat performance may be the direct result of the function, or a second
function may be triggered that, in turn, refers back to the first function.
Working of Recursion in C++
voidrecurse()
{
... .. ...
recurse();
... .. ...
}
intmain()
{
... .. ...
recurse();
... .. ...
}
176
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
The figure below shows how recursion works by calling itself over and over again.
n s
c a tio
b l i
P u
a h ul
R
177
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s [a]
tio
(a) O(1) (b) O(n)
(c) O(logn) (d) O(nlogn)
5.
i c a
Which one of the following is the correct way to increment the rear end in a circular queue? [ b ]
l
(a) rear =rear+1
b
(b) (rear+1) % max
Pu
(c) (rear % max) + 1 (d) None of the above
6.
ul
In the linked list implementation of queue, where will the new element be inserted?
(a) At the middle position of the linked list (b) At the head position of the linked list
[c]
7.
(c)
ah
At the tail position of the linked list
R
How many Queues are required to implement a Stack?
(a) 3
(d) None of the above
(b) 2
[b]
(c) 1 (d) 4
8. Which one of the following is not the application of the Queue data structure? [d]
(a) Resource shared between various systems (b) Data is transferred asynchronously
(c) Load balancing (d) Balancing of symbols
9. Which of the following principle is used if two elements in the priority queue have the same priority?
[b]
(a) LIFO (b) FIFO
(c) Linear tree (d) None of the above
10. A linear data structure in which insertion and deletion operations can be performed from both the
ends is . [b]
(a) Queue (b) Deque
(c) Priority queue (d) Circular queue
178
Rahul Publications
UNIT - II DATA STRUCTURES USING C++
n s
tio
8. Linked List can be defined as collection of objects called that are randomly stored in the
memory.
9. The doubly linked list can be accessed in
l i c a
directions.
10.
b
is a more complexed type of data structure in which a node contain pointers to its
u
previous node as well as the next node.
ul P ANSWERS
1. O(n)
a h
2.
3.
4.
R
recursive function
direct recursion
isEmpty()
5. Ring Buffer
6. Double Ended Queue
7. priority queue
8. nodes
9. both
10. Circular doubly linked list
179
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Circular doubly linked list is a more complexed type of data structure in which a node contain
pointers to its previous node as well as the next node.
2. Single Linked List
Ans :
The singly linked list is a data structure that contains two parts, i.e., one is the data part, and the
other one is the address part, which contains the address of the next or the successor node. The address
part in a node is also known as a pointer.
3. Linked List
Ans :
n s
a tio
A linked list can also be defined as the collection of the nodes in which one node is connected to
another node, and node consists of two parts, i.e., one is the data part and the second one is the address
c
part.
4. What is recursion?
b l i
Ans :
P u
h
called the recursive function
a ul
The process in which a function calls itself is known as recursion and the corresponding function is
5.
Ans : R
Priority Queue
A priority queue is a special type of queue in which each element is associated with a priority and is
served according to its priority. If elements with the same priority occur, they are served according to their
order in the queue.
180
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Trees: Introduction, Types of Trees, Binary Tree, Binary Tree Abstract Data
Type, Realization of a Binary Tree, Insertion of a Node in Binary Tree, Binary
Tree Traversal, Other Tree Operations, Binary Search Tree, Threaded Binary
UNIT Tree, Applications of Binary Trees.
Searching and Sorting: Search Techniques-Linear Search, Binary Search,
III Sorting TechniquesSelection Sort, Bubble Sort, Insertion Sort, Merge Sort,
Quick Sort, Comparison of All Sorting Methods, Search Trees: Symbol Table,
Optimal Binary Search Tree, AVL Tree (Heightbalanced Tree).
3.1 TREES
3.1.1 Introduction
Q1. What is tree data structure? Write about the basic terminology of tree data structure.
Ans :
A tree data structure can also be defined as follows:
n s
tio
Tree data structure is a collection of data (Node) which is organized in hierarchical structure and this
is a recursive definition
l i c a
In tree data structure, every individual element is called as Node. Node in a tree data structure,
stores the actual data of that particular element and link to next element in hierarchical structure.
u b
In a tree data structure, if we have N number of nodes then we can have a maximum of N-
1 number of links.
Example:
ul P
a h
R TREE with 11nodes and 10 edges
- In any tree with 'N'nodes there
will be maximum of 'N-1' edges
- In a tree every individual
element is called as 'NODE'
Terminology
In a tree data structure, we use the following terminology.
1. Root
In a tree data structure, the first node is called as Root Node. Every tree must have root node. We
can say that root node is the origin of tree data structure. In any tree, there must be only one root
node. We never have multiple root nodes in a tree.
181
Rahul Publications
B.Sc. II YEAR III SEMESTER
2. Edge
In a tree data structure, the connecting link between any two nodes is called as EDGE. In a tree
with ‘N’ number of nodes there will be a maximum of ‘N-1’ number of edges.
s
- In any tree, 'Edge' is a connecting
n
tio
link between two nodes.
l i c a
u b
3. Parent
ul P
In a tree data structure, the node which is predecessor of any node is called as PARENT NODE. In
a h
simple words, the node which has branch from it to any other node is called as parent node. Parent
node can also be defined as “The node which has child / children”.
R
Here A, B, C, E & G are parent nodes
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD Node. In
simple words, the node which has a link from its parent node is called as child node. In a tree, any
parent node can have any number of child nodes. In a tree, all the nodes except root are child
nodes.
182
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple
words, the nodes with same parent are called as Sibling nodes.
Here B & C are Siblings
Here DE & F are Siblings
Here G & H are Siblings
Here I & J are Siblings
s
- In any tree the nodes which has
n
tio
same Parent are called 'Siblings'
i a
- The children of a Parent are
c
called 'Siblings'
l
6. Leaf
u b
ul P
In a tree data structure, the node which does not have a child is called as LEAF Node. In simple
words, a leaf is a node with no child.
a h
In a tree data structure, the leaf nodes are also called as External Nodes. External node is also a
node with no child. In a tree, leaf node is also called as ‘Terminal’ node.
R
Here D, I, J, F, K & H are Leaf nodes'
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In
simple words, an internal node is a node with atleast one child.
183
Rahul Publications
B.Sc. II YEAR III SEMESTER
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root node
is also said to be Internal Node if the tree has more than one node. Internal nodes are also called
as ‘Non-Terminal’ nodes.
Here Degree of B is 3
n s
Here Degree of A is 2
Here Degree of F is 0
c a tio
b l i
- In any tree, 'Degree' a node is total
ul
9. Level
a h
In a tree data structure, the root node is said to be at Level 0 and the children of root node are at
Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so on... In simple
R
words, in a tree each step from top to bottom is called as a Level and the Level count starts with ‘0’
and incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of egdes from leaf node to a particular node in the longest
path is called as HEIGHT of that Node. In a tree, height of the root node is said to be height of
the tree. In a tree, height of all leaf nodes is ‘0’.
184
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
11. Depth
In a tree data structure, the total number of egdes from root node to a particular node is called
as DEPTH of that Node. In a tree, the total number of edges from root node to a leaf node in the
longest path is said to be Depth of the tree. In simple words, the highest depth of any leaf node in
a tree is said to be depth of that tree. In a tree, depth of the root node is ‘0’.
Here Depth of tree is 3
s
- In any tree, 'Depth of Node' is
n
tio
total number of Edges from root
l i a
to that node.
c
- In any tree, 'Depth of Tree' is
12. Path
ul P to leaf in the longest path.
a h
In a tree data structure, the sequence of Nodes and Edges from one node to another node is called
R
as PATH between that two Nodes. Length of a Path is total number of nodes in that path. In
below example the path A - B - E - J has length 4.
A-B-E-J
185
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
1. Free tree
2. Rooted tree
3. Ordered tree
4. Regular tree
n s
5. Binary tree
c a tio
6.
7.
Complete tree
Position tree
b l i
1. Free tree
P u
ul
A free tree is a connected, acyclic graph. It is an undirected graph. It has no node designated as a
h
root. As it is connected, any node can be reached from any other node through a unique path. The
a
following is an example of a free tree.
R
2. Rooted tree
Unlike free tree, a rooted tree is a directed graph where one node is designated as root, whose
incoming degree is zero, whereas for all other nodes, the incoming degree is one.
186
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
3. Ordered tree
In many applications, the relative order of the nodes at any particular level assumes some significance.
It is easy to impose an order on the nodes at a level by referring to a particular node as the first
node, to another node as the second, and so on. Such ordering can be done from left to right . Just
like nodes at each level, we can prescribe order to edges. If in a directed tree, an ordering of a node
at each level is prescribed, then such a tree is called an ordered tree.
4. Regular tree
A tree where each branch node vertex has the same outdegree is called a regular tree. If in a
directed tree, the outdegree of every node is less than or equal to m, then the tree is called an m-
s
ary tree. If the outdegree of every node is exactly equal to m (the branch nodes) or zero (the leaf
n
tio
nodes), then the tree is called a regular m-ary tree.
5. Binary tree
i c a
A binary tree is a special form of an m-ary tree. Since a binary tree is important, it is frequently used
in various applications of computer science.
l
u b
We have defined an m-ary tree (general tree). A binary tree is an m-ary position tree
6. Complete tree
ul P
when m =2. In a binary tree, no node has more than two children.
a h
A tree with n nodes and of depth k is complete if and only if its nodes correspond to the nodes that
R
are numbered from 1 to n in the full tree of depth k.
A binary tree of height h is complete if and only if one of the following holds good:
1. It is empty.
2. Its left subtree is complete of height h>=1 and its right subtree is completely full of
height h =2.
3. Its left subtree is completely full of height h >=1 and its right subtree is complete of
height h =1.
A binary tree is completely full if it is of height h and has (2h+1 -1) nodes.
Full binary tree : A binary tree is a full binary tree if it contains the maximum possible number of
nodes in all levels.
In a full binary tree, each node has two children or no child at all. The total number of nodes in a
full binary tree of heighth is 2h+1-1 considering the root at level 0.
It can be calculated by adding the number of nodes of each level as in the following equation:
20 <21 <22 <... <2h <2h+1 -1
187
Rahul Publications
B.Sc. II YEAR III SEMESTER
Complete binary tree A binary tree is said to be a complete binary tree if all its levels except the last
level have the maximum number of possible nodes, and all the nodes of the last level appear as far
left as possible. In a complete binary tree, all the leaf nodes are at the last and the second last level,
and the levels are filled from left to right.
Left skewed binary tree If the right subtree is missing in every node of a tree, we call it a left skewed
tree . If the left subtree is missing in every node of a tree, we call it as right subtree.
Strictly binary tree If every non-terminal node in a binary tree consists of non-empty left and
right subtrees, then such a tree is called a strictly binary tree.
n s
tio
In Fig. the non-empty nodes D and E have left and right subtrees. Such expression trees are known
a
as strictly binary trees.
b l i c
Extended binary tree A binary tree T with each node having zero or two children is called an
extended binary tree. The nodes with two children are called internal nodes, and those with zero
7. Position tree
P u
children are called external nodes. Trees can be converted into extended trees by adding a node.
ul
A position tree, also known as a suffix tree, is one that represents the suffixes of a string S and such
h
representation facilitates string operations being performed faster. Such a tree’s edges are labelled
a
with strings, such that each suffix of S corresponds to exactly one path from the tree’s root to a leaf
R
node. The space and time requirement is linear in the length of S. After its construction, several
operations can be performed quickly, such as locating a substring in S, locating a substring if a
certain number of mistakes are allowed, locating matches for a regular expression pattern, and so
3.1.3 Binary Tree
Q3. What is binary tree?
(OR)
Properties of binary tree.
Ans : (Nov.-2017)
In a normal tree, every node can have any number of children. Binary tree is a special type of tree
data structure in which every node can have a maximum of 2 children. One is known as left child and the
other is known as right child.
A tree in which every node can have a maximum of two children is called as Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children but not more than
2 children.
188
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Example
n s
tio
A binary tree in which every node has either two or zero number of children is called Strictly Binary
Tree
i c a
Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree
l
u b
ul P
a h
R
Strictly binary tree data structure is used to represent mathematical expressions.
Example
189
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
A binary tree can be converted into Full Binary tree by adding dummy nodes to existing nodes
wherever required.
Tree.
l i c a
The full binary tree obtained by adding dummy nodes to a binary tree is called as Extended Binary
u b
ul P
a h
R
In above figure, a normal binary tree is converted into full binary tree by adding dummy nodes (In
pink colour).
3.1.4 Binary Tree Abstract Data Type
Q5. Explain ADT of Binary Tree
Ans :
A binary tree consists of nodes with one predecessor and at most two successors (called the left child
and the right child). The only exception is the root node of the tree that does not have a predecessor. A
node can contain any amount and any type of data.
1. create: A binary tree may be created in several states. The most common include.
an empty tree (i.e. no nodes) and hence the constructor will have no parameters
a tree with one node (i.e. the root) and hence the constructor will have a single parameter (the
data for the root node)
190
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
a tree with a new root whose children are other existing trees and hence the constructor will
have three parameters (the data for the root node and references to its subtrees)
2. isEmpty(): Returns true if there are no nodes in the tree, false otherwise.
isFull(): May be required by some implementations. Returns true if the tree is full, false
otherwise.
3. clear(): Removes all of the nodes from the tree (essentially reinitializing it to a new empty tree).
4. add(value): Adds a new node to the tree with the given value. The actual implementation of this
method is determined by the purpose for the tree and how the tree is to be maintained and/or
processed. To begin with, we will assume no particular purpose or order and therefore add new
nodes in such a way that the tree will remain nearly balanced.
5. remove(): Removes the root node of the tree and returns its data. The actual implementation of
this method and other forms of removal will be determined by the purpose for the tree and how
the tree is to be maintained and/or processed. For example, you might need a remove() method
with a parameter that indicates which node of the tree is to be removed (based on position, key
data, or reference). To begin with, we will assume no particular purpose or order and therefore
remove the root in such a way that the tree will remain nearly balanced.
Other operations that may be included as needed:
n s
tio
height(): Determines the height of the tree. An empty tree will have height 0.
size(): Determines the number of nodes in the tree.
i c a
getRootData(): Returns the data (primative data) or reference to the data (objects) of the tree’s
l
root.
u b
getLeftSubtree(): Returns a reference to the left subtree of this tree.
ul P
getRightSubtree(): Returns a reference to the right subtree of this tree.
Q6.
a h
3.1.5 Realization of a Binary Tree
Explain various methods of representing a binary tree.
Ans : R
A binary tree data structure is represented using two methods. Those methods are as follows:
1. Array Representation
2. Linked List Representation
Consider the following binary tree:
191
Rahul Publications
B.Sc. II YEAR III SEMESTER
1. Array Representation
In array representation of binary tree, we use a one dimensional array (1-D Array) to represent a
binary tree.
A B C D F G H I J K
To represent a binary tree of depth ’n’ using array representation, we need one dimensional array
with a maximum size of 2n+1 – 1.
Advantages
The various merits of representing binary trees using arrays are as follows:
1. Any node can be accessed from any other node by calculating the index.
2.
s
Here, the data is stored without any pointers to its successor or predecessor.
n
tio
3. In the programming languages, where dynamic memory allocation is not possible (such as BASIC,
fortran ), array represen-tation is the only means to store a tree.
Disadvantages
l i c a
u b
The various demerits when representing binary trees using arrays are as follows:
1.
ul P
Other than full binary trees, majority of the array entries may be empty.
2.
h
It allows only static representation. The array size cannot be changed during the execution.
a
3.
R
Inserting a new node to it or deleting a node from it is inefficient with this representation, because
it requires considerable data movement up and down the array, which demand excessive amount
of processing time.
We use double linked list to represent a binary tree. In a double linked list, every node consists of
three fields. First field for storing left child address, second for storing actual data and third for
storing right child address.
The above example of binary tree represented using Linked list representation is shown as follows:
192
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Q7. Write aC++ program to create a Complete Binary tree from its Linked List
Representation.
Ans :
#include <iostream>
n s
// C++ program to create a Complete Binary tree from its Linked ListRepresentation
#include <string>
#include <queue>
c a tio
using namespace std;
b l i
// Linked list node
P u
ul
struct ListNode
{
int data;
a h
}; R
ListNode* next;
193
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
queue<BinaryTreeNode *> q;
// Base Case
{
if (head == NULL)
l i c a
u b
root = NULL; // Note that root is passed by reference
}
return;
ul P
a h
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
R
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
194
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
q.push(leftChild);
head = head->next;
if (head)
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
n s
tio
{ if (root)
{
inorderTraversal( root->left );
l i c a
cout << root->data << “ “;
u b
}
ul P
inorderTraversal( root->right );
a h
// Driver program to test above functions
int main()
{
R
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << “Inorder Traversal of the constructed Binary Tree is: \n”;
195
Rahul Publications
B.Sc. II YEAR III SEMESTER
inorderTraversal(root);
return 0;
}
Run on IDE
Output:
Inorder Traversal of the constructed Binary Tree is:
25 12 30 10 36 15
3.1.6 Insertion of a Node in Binary Tree
Q8. How to insert a node in binary tree? Explain with an example.
Ans :
The insert() operation inserts a new node at any position in a binary tree. The node to be inserted
could be a branch node or a leaf node. The branch node insertion is generally based on some criteria that
are usually in the context of a special form of a binary tree.
Let us study a commonly used case of inserting a node as a leaf node.
The insertion procedure is a two-step process.
n s
tio
1. Search for the node whose child node is to be inserted. This is a node at some level i, and a node
is to be inserted at the level i >1 as either its left child or right child. This is the node after which the
2.
insertion is to be made.
l i c a
Link a new node to the node that becomes its parent node, that is, either the Lchild or the Rchild.
Example: insert 60 in the tree:
u b
1.
2.
ul P
start at the root, 60 is greater than 25, search in right subtree
60 is greater than 50, search in 50’s right subtree
3.
h
60 is less than 70, search in 70’s left subtree
a
4.
R
60 is less than 66, add 60 as 66’s left child
196
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Q9. Write a C++ program to insert an //function to display all the element present
element into binary tree in the binary tree
n s
tio
q.push(root);
{ // Do level order traversal until we find an
Node* temp = new Node();
l i c a
empty place.
b
temp->data = data; while (!q.empty()) {
Pu
temp->left = temp->right = NULL; structNode* root = q.front();
}
return temp;
ul q.pop();
if (!root->left) {
{
R ah
// A function to create binary tree.
Node* Tree(Node* temp, int data ) break;
root->left = newNode(value);
} else
// If the tree is empty, return a new node q.push(root->left);
if (temp == NULL) if (!root->right) {
return newNode(data); root->right = newNode(value);
// Otherwise, recur down the tree break;
if (data < temp->data) } else
temp->left = Tree(temp->left, data); q.push(root->right);
else }
temp->right = Tree(temp->right, data); }
//return the (unchanged) node pointer intmain()
return temp; {
} char ch;
197
Rahul Publications
B.Sc. II YEAR III SEMESTER
int n, arr[20],size;
Node *root = new Node;
root = NULL;
cout<<“Enter the size of array : “;
cin>>size;
cout<<“Enter the elements in array : “;
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
// Construct the binary tree.
for(int i = 0; i < size; i++)
{
root = Tree(root, arr[i]);
}
n s
tio
cout<<“\nEnter the Element to be insert : “;
cin>>n;
insert(root,n);
l i c a
cout<<“\nElement Inserted”<<endl;
u
cout<<“\nAfter Inserting “<<endl; b
cout<<“Elements are: “;
display(root);
ul P
cout<<endl;
a h
return0;
} R
3.1.7 Binary Tree Traversal
Q10. Explain about various traversal techniques of binary tree.
Ans : (July-21, Dec.-19, June-19, Dec.-18, June-18)
When we wanted to display a binary tree, we need to follow some order in which all the nodes of
that binary tree must be displayed. In any binary tree displaying order of nodes depends on the traversal
method.
Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
There are three types of binary tree traversals.
1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal
Consider the following binary tree:
198
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
a root node for left subtree. so we try to visit its (B’s) left child ‘D’ and again D is a root for subtree
with nodes D, I and J. So we try to visit its left child ‘I’ and it is the left most child. So first we
tio
visit ’I’ then go for its root node ’D’ and later we visit D’s right child ’J’. With this we have
completed the left part of node B. Then visit ’B’ and next B’s right child ’F’ is visited. With this we
l i c a
have completed left part of node A. Then visit root node ’A’. With this we have completed left and
root parts of node A. Then we go for right part of the node A. In right of A again there is a subtree
u b
with root C. So go for left child of C and again it is a subtree with root G. But G does not have left
part so we visit ’G’ and then visit G’s right child K. With this we have completed the left part of
ul
the tree so we stop the process. P
node C. Then visit root node ’C’ and next visit C’s right child ’H’ which is the right most child in
Traversal.
a h
That means here we have visited in the order of I - D - J - B - F - A - G - K - C - H using In-Order
R
In-Order Traversal for above example of binary tree is
I-D-J-B-F-A-G-K-C-H
2. Pre - Order Traversal ( root - leftChild - rightChild )
In Pre-Order traversal, the root node is visited before left child and right child nodes. In this traversal,
the root node is visited first, then its left child and later its right child. This pre-order traversal is
applicable for every root node of all subtrees in the tree.
In the above example of binary tree, first we visit root node ’A’ then visit its left child ’B’ which is
a root for D and F. So we visit B’s left child ’D’ and again D is a root for I and J. So we visit D’s left
child ’I’ which is the left most child. So next we go for visiting D’s right child ’J’. With this we have
completed root, left and right parts of node D and root, left parts of node B. Next visit B’s right
child ’F’. With this we have completed root and left parts of node A. So we go for A’s right
child ’C’ which is a root node for G and H. After visiting C, we go for its left child ’G’ which is a
root for node K. So next we visit left of G, but it does not have left child so we go for G’s right
child ’K’. With this we have completed node C’s root and left parts. Next visit C’s right child ’H’ which
is the right most child in the tree. So we stop the process.
199
Rahul Publications
B.Sc. II YEAR III SEMESTER
l i c a
tree_node *parent;
p->data=item;
traversal of a Binary Tree
b
Pu
p->left=NULL;
Ans : (Dec.-19, July-19, June-18)
p->right=NULL;
#include<iostream.h>
ul parent=NULL;
ah
#include<conio.h> if(isempty())
#include<process.h> root=p;
struct tree_node
{
R else
{
tree_node *ptr;
tree_node *left;
ptr=root;
tree_node *right;
while(ptr!=NULL)
int data; {
}; parent=ptr;
class bst if(item>ptr->data)
{ ptr=ptr->right;
200
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
else preorder(ptr->right);
parent->right=p; }
} }
}
void main()
void bst::inordertrav()
{ {
inorder(root); bst b;
} b.insert(52);
void bst::inorder(tree_node *ptr)
b.insert(25);
{
b.insert(50);
if(ptr!=NULL)
{ b.insert(15);
inorder(ptr->left); b.insert(40);
cout<<“ “<<ptr->data<<“ “; b.insert(45);
inorder(ptr->right);
b.insert(20); cout<<“inorder”<<endl;
}
}
b.inordertrav();
n s
void bst::postordertrav()
{
c a tio
cout<<endl<<“postorder”<<endl;
b.postordertrav();
}
postorder(root);
b l i
cout<<endl<<“preorder”<<endl;
Pu
b.preordertrav();
void bst::postorder(tree_node *ptr)
{
if(ptr!=NULL)
ul }
getch();
R ah
postorder(ptr->left);
postorder(ptr->right);
3.1.8 Other Tree Operations
Q12. Explain about other tree operations on
a binary tree.
cout<<“ “<<ptr->data<<“ “;
} Ans :
} Using traversal as a basic operation, many
void bst::preordertrav() other operations can be performed on a tree, such
{ as finding the height of the tree, computing the total
number of nodes, leaf nodes, and so on. Let us
preorder(root); study a few of such operations.
}
counting nodes : CountNode() is the
void bst::preorder(tree_node *ptr) function that returns the total count of nodes
{ in a linked binarytree.
if(ptr!=NULL)
int BinaryTree :: CountNode(TreeNode
{ *Root)
cout<<“ “<<ptr->data<<“ “; {
preorder(ptr->left); if(Root == Null)
201
Rahul Publications
B.Sc. II YEAR III SEMESTER
return 0;
else
return(1 + CountNode(Root->Rchild) + CountNode(Root->Lchild));
}
counting leaf nodes : The CountLeaf() operation counts the total number of leaf nodes in a
linked binary tree.Leaf nodes are those with no left or right children.
int BinaryTree :: CountLeaf(TreeNode *Root)
{
if(Root == Null)
return 0;
else if((Root->Rchild == Null) && (Root->Lchild == Null))
return(1);
else
return(CountLeaf(Root->Lchild) + CountLeaf(Root->Rchild));
n s
tio
}
Computing Height of Binary Tree : The TreeHeight() operation computes the height of a linked
l i c a
binary tree. Height of atree is the maximum path length in the tree. We can get the path length by
traversing thetree depthwise. Let us consider that an empty tree’s height is 0 and the tree with only
onenode has the height 1.
u
int BinaryTree :: TreeHeight(TreeNode *Root) b
{
ul P
a
if(Root == Null) h
int heightL, heightR;
return 0;
R
if(Root->Lchild == Null && Root->Rchild == Null)
return 0;
heightL = TreeHeight(Root->Lchild);
heightR = TreeHeight(Root->Rchild);
if(heightR > heightL)
return(heightR + 1);
return(heightL + 1);
}
Getting Mirror, Replica, or Tree Interchange of Binary Tree : The Mirror() operation finds the
mirror of the tree that will interchange all left and rightsubtrees in a linked binary tree.
void BinaryTree :: Mirror(TreeNode *Root)
{
202
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
TreeNode *Tmp;
if(Root != Null)
{
Tmp = Root->Lchild;
Root->Lchild = Root->Rchild;
Root->Rchild = Tmp;
Mirror(Root->Lchild);
Mirror(Root->Rchild);
}
}
Copying Binary Tree: The TreeCopy() operation makes a copy of the linked binary tree. The
function shouldallocate the necessary nodes and copy the respective contents into them.
TreeNode *BinaryTree :: TreeCopy()
{
TreeNode *Tmp;
n s
if(Root == Null)
return Null;
c a tio
Tmp = new TreeNode;
b l i
u
Tmp?Lchild = TreeCopy(Root?Lchild);
P
ul
Tmp?Rchild = TreeCopy(Root?Rchild);
Tmp?Data = Root?Data;
return Tmp;
a h
}
R
Equality Test : The BTree_Equal() operation checks whether two binary trees are equal. Two
trees aresaid to be equal if they have the same topology, and all the corresponding nodes are
equal.The same topology refers to the fact that each branch in the first tree corresponds to abranch
in the second tree in the same order and vice versa.
int BinaryTree :: BTree_Equal(Binarytree T1 , BinaryTree T2)
{
if(Root == Null && T2.Root == Null)
return 1;
return(Root && T2.Root);
&&(Root->Data == T2.Root->Data);
&&BTree_Equal(Root->Lchild ,T2.Root->Lchild);
&&BTree_Equal(Root->Rchild, T2.Root->Rchild));
}
203
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
c a tio
b l i
P u
a h ul
R
We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher
valued keys on the right sub-tree.
In a binary search tree, all the nodes in left subtree of any node contains smaller values and all the
nodes in right subtree of that contains larger values as shown in following figure.
204
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Example
The following tree is a Binary Search Tree. In this tree, left subtree of every node contains nodes
with smaller values and right subtree of every node contains larger values.
Every Binary Search Tree is a binary tree but all the Binary Trees need not to be binary search trees.
c a tio (Nov.-17)
Operations on a Binary Search Tree
b l i
The following operations are performed on a binary search tree...
1. Search
P u
ul
2. Insertion
3. Deletion
1.
a h
Search Operation in BST
R
In a binary search tree, the search operation is performed with O(log n) time complexity. The
search operation is performed as follows...
Step 1: Read the search element from the user
Step 2: Compare, the search element with the value of root node in the tree.
Step 3: If both are matching, then display “Given node found!!!” and terminate the function
Step 4: If both are not matching, then check whether search element is smaller or larger than that
node value.
Step 5: If search element is smaller, then continue the search process in left subtree.
Step 6: If search element is larger, then continue the search process in right subtree.
Step 7: Repeat the same until we found exact element or we completed with a leaf node
Step 8: If we reach to the node with search value, then display “Element is found” and terminate
the function.
Step 9: If we reach to a leaf node and it is also not matching, then display “Element not found”
and terminate the function.
205
Rahul Publications
B.Sc. II YEAR III SEMESTER
Algorithm
struct node* search(int data){
struct node *current = root;
printf(“Visiting elements: “);
while(current->data != data){
if(current != NULL){
printf(“%d “,current->data);
//go to left tree
if(current->data > data){
current = current->leftChild;
}//else go to right tree
else{
current = current->rightChild;
}
n s
tio
//not found
if(current == NULL){
return NULL;
l i c a
}}}
u b
return current;
}
ul P
2.
h
Insertion Operation in BST
a
as follows: R
In a binary search tree, the insertion operation is performed with O(log n) time complexity. In
binary search tree, new node is always inserted as a leaf node. The insertion operation is performed
Step 1: Create a newNode with given value and set its left and right to NULL.
Step 2: Check whether tree is Empty.
Step 3: If the tree is Empty, then set set root to newNode.
Step 4: If the tree is Not Empty, then check whether value of newNode is smaller or larger than
the node (here it is root node).
Step 5: If newNode is smaller than or equal to the node, then move to its left child. If newNode
is larger than the node, then move to its right child.
Step 6: Repeat the above step until we reach to a leaf node (e.i., reach to NULL).
Step 7: After reaching a leaf node, then isert the newNode as left child if newNode is smaller or
equal to that leaf else insert it as right child.
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
206
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
using search operation
tio
current = current->leftChild; Step 2: If it has only one child, then create
a link between its parent and child nodes.
//insert to the left
if(current == NULL) {
l i c a
Step 3: Delete the node using free function
parent->leftChild = tempNode;
b and terminate the function.
Pu
return; Case 3: Deleting a node with two children
}
ah
}//go to right of the tree
else { Step 1: Find the node to be deleted
R
current = current->rightChild;
//insert to the right
using search operation
Step 2: If it has two children, then find
if(current == NULL) { the largest node in its left subtree (OR)
parent->rightChild = tempNode; the smallest node in its right subtree.
207
Rahul Publications
B.Sc. II YEAR III SEMESTER
Example
Construct a Binary Search Tree by inserting the following sequence of numbers.
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows.
n s
c a tio
b l i
P u
a h ul
R
Q15. Write a program to implement BST.
Ans :
/* * C++ Program To Implement BST */
# include <iostream>
# include <cstdlib>
using namespace std;
/* * Node Declaration */
struct node
{
int info;
208
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
c a tio
}
root = NULL;
b l i
};
P u
ul
/* * Main Contains Menu */
int main()
{
a h
R
int choice, num;
BST bst;
node *temp;
while (1)
{
cout<<“————————”<<endl;
cout<<“Operations on BST”<<endl;
cout<<“————————”<<endl;
cout<<“1.Insert Element “<<endl;
cout<<“2.Delete Element “<<endl;
cout<<“3.Inorder Traversal”<<endl;
cout<<“4.Preorder Traversal”<<endl;
cout<<“5.Postorder Traversal”<<endl;
cout<<“6.Display”<<endl;
cout<<“7.Quit”<<endl;
cout<<“Enter your choice : “;
209
Rahul Publications
B.Sc. II YEAR III SEMESTER
cin>>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<“Enter the number to be inserted : “;
cin>>temp->info;
bst.insert(root, temp);
case 2:
if (root == NULL)
{
cout<<“Tree is empty, nothing to delete”<<endl;
continue;
}
cout<<“Enter the number to be deleted : “;
cin>>num;
bst.del(num);
n s
break;
case 3:
c a tio
cout<<“Inorder Traversal of BST:”<<endl;
bst.inorder(root);
b l i
cout<<endl;
P u
ul
break;
case 4:
a h
cout<<“Preorder Traversal of BST:”<<endl;
R
bst.preorder(root);
cout<<endl;
break;
case 5:
cout<<“Postorder Traversal of BST:”<<endl;
bst.postorder(root);
cout<<endl;
break;
case 6:
cout<<“Display BST:”<<endl;
bst.display(root,1);
cout<<endl;
break;
case 7:
exit(1);
default:
210
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
{
if (item == root->info) {
n s
cout<<“Element already in the
tio
*loc = root; tree”<<endl;
*par = NULL;
return;
l
}
i c a return;
}
if (item < root->info)
u b if (tree->info > newnode->info)
{
ptr = root->left;
else
ul P if (tree->left != NULL)
{
a h
ptr = root->right; insert(tree->left, newnode);
{
R
ptrsave = root;
while (ptr != NULL)
}
else
{
if (item == ptr->info) tree->left = newnode;
{ (tree->left)->left = NULL;
*loc = ptr; (tree->left)->right = NULL;
*par = ptrsave; cout<<“Node Added To Left”<<endl;
return; return;
} }
ptrsave = ptr; }
if (item < ptr->info) else
ptr = ptr->left; {
else if (tree->right != NULL)
ptr = ptr->right; {
} insert(tree->right, newnode);
*loc = NULL; }
211
Rahul Publications
B.Sc. II YEAR III SEMESTER
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<“Node Added To Right”<<endl;
return;
}
}}
/* * Delete Element from the tree */
void BST::del(int item)
{
node *parent, *location;
if (root == NULL)
{
cout<<“Tree empty”<<endl;
n s
tio
return;
}
find(item, &parent, &location);
if (location == NULL)
l i c a
{
u b
return;
ul P
cout<<“Item not present in tree”<<endl;
a h
if (location->left == NULL && location->right == NULL)
R
case_a(parent, location);
if (location->left != NULL && location->right == NULL)
case_b(parent, location);
if (location->left == NULL && location->right != NULL)
case_b(parent, location);
if (location->left != NULL && location->right != NULL)
case_c(parent, location);
free(location);
}
/* * Case A */
void BST::case_a(node *par, node *loc )
{
if (par == NULL)
{
root = NULL;
212
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
} parsuc = ptrsave;
else if (suc->left == NULL && suc->right
{ == NULL)
if (loc == par->left) case_a(parsuc, suc);
par->left = NULL; else
else case_b(parsuc, suc);
par->right = NULL; if (par == NULL)
} {
} root = suc;
/* * Case B */ }
void BST::case_b(node *par, node *loc) else
{ {
node *child; if (loc == par->left)
if (loc->left != NULL) par->left = suc;
child = loc->left; else
else
child = loc->right; }
n s
par->right = suc;
if (par == NULL)
{
a tio
suc->left = loc->left;
suc->right = loc->right;
c
}
root = child;
b l
}
i
/* * Pre Order Traversal */
else
ul
{ {
if (loc == par->left) if (root == NULL)
a h
par->left = child; {
}
else
R
par->right = child;
}
cout<<“Tree is empty”<<endl;
return;
} if (ptr != NULL)
/* * Case C */ {
void BST::case_c(node *par, node *loc) cout<<ptr->info<<“ “;
{ preorder(ptr->left);
node *ptr, *ptrsave, *suc, *parsuc; preorder(ptr->right);
ptrsave = loc; }
ptr = loc->right; }
while (ptr->left != NULL) /* * In Order Traversal */
{
ptrsave = ptr; void BST::inorder(node *ptr)
ptr = ptr->left; {
} if (root == NULL)
suc = ptr; {
213
Rahul Publications
B.Sc. II YEAR III SEMESTER
cout<<“Tree is empty”<<endl; }
return; cout<<ptr->info;
} display(ptr->left, level+1);
if (ptr != NULL) }
{ }
inorder(ptr->left); OUTPUT
cout<<ptr->info<<“ “; ————————
inorder(ptr->right);
Operations on BST
}
————————
}
1. Insert Element
/* * Postorder Traversal */
2. Delete Element
void BST::postorder(node *ptr)
3. Inorder Traversal
{
4. Preorder Traversal
if (root == NULL)
5. Postorder Traversal
{
6. Display
cout<<“Tree is empty”<<endl;
7. Quit
n s
tio
return;
Enter your choice : 1
}
if (ptr != NULL)
{
l i c a
Enter the number to be inserted : 8
Root Node is Added
b ————————
Pu
postorder(ptr->left);
Operations on BST
postorder(ptr->right);
cout<<ptr->info<<“ “;
ul ————————
1. Insert Element
ah
}
2. Delete Element
}
R
/* * Display Tree Structure */
void BST::display(node *ptr, int level)
3.
4.
5.
Inorder Traversal
Preorder Traversal
Postorder Traversal
{
6. Display
int i;
7. Quit
if (ptr != NULL)
Enter your choice : 6
{
Display BST:
display(ptr->right, level+1);
Root->: 8
cout<<endl;
————————
if (ptr == root)
Operations on BST
cout<<“Root->: “;
————————
else
1. Insert Element
{
for (i = 0;i < level;i++) 2. Delete Element
214
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
tio
5. Postorder Traversal
6. Display
7. Quit
l i c a
Enter your choice : 6
u b
Display BST : 9
Root->: 8
a h tree.
R
Q16. What is threaded binary tree? Explain
the representation of threaded binary
tree.
In-order traversal of above binary tree:
H-D-I-B-E-A-F-J-C-G
When we represent above binary tree using
Ans : linked list representation, nodes H, I, E, F,
A binary tree is represented using array J and G left child pointers are NULL. This NULL
representation or linked list representation. When is replaced by address of its in-order predecessor,
a binary tree is represented using linked list respectively (I to D, E to B, F to A, J to F and G
representation, if any node is not having a child we to C), but here the node H does not have its in-
use NULL pointer in that position. In any binary order predecessor, so it points to the root node A.
tree linked list representation, there are more And nodes H, I, E, J and G right child pointers
number of NULL pointer than actual pointers. are NULL. This NULL ponters are replaced by
Generally, in any binary tree linked list address of its in-order successor, respectively (H to
representation, if there are 2N number of reference D, I to B, E to A, and J to C), but here the node G
fields, then N+1 number of reference fields are does not have its in-order successor, so it points to
filled with NULL ( N+1 are NULL out of 2N ). the root node A.
This NULL pointer does not play any role except Above example binary tree become as follows
indicating there is no link (no child). after converting into threaded binary tree.
215
Rahul Publications
B.Sc. II YEAR III SEMESTER
tio
void insert(int key)
Binary Tree
{
#include <iostream>
#include <cstdlib>
l i c aNode *p = root;
Pu
usingnamespace std; {
/* Class Node */
class Node
ul if(p->key < key)
{
{
public:
int key; R ah if(p->rightThread)
break;
p = p->right;
Node *left, *right; }
bool leftThread, rightThread; elseif(p->key > key)
};
{
/* Class ThreadedBinarySearchTree */
if(p->leftThread)
class ThreadedBinarySearchTree
break;
{
p = p->left;
private:
}
Node *root;
public: else
/* Constructor */ {
ThreadedBinarySearchTree() /* redundant key */
{ return;
216
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
} {
} if(tmp->leftThread)
Node *tmp =new Node(); returnfalse;
tmp->key = key; tmp = tmp->left;
tmp->rightThread = tmp->left }
Thread =true; else
if(p->key < key) {
{ returntrue;
/* insert to right side */ }
tmp->right = p->right; }}
tmp->left = p; /* Fuction to delete an element */
p->right = tmp; void Delete(int key)
p->rightThread =false; {
}
s
Node *dest = root->left, *p = root;
n
tio
else for(;;)
{ {
tmp->right = p;
i c a
if(dest->key < key)
l
tmp->left = p->left;
b {
Pu
p->left = tmp; /* not found */
ul
p->leftThread =false; if(dest->rightThread)
ah
} return;
} p = dest;
R
/* Function to search for an element */
bool search(int key) }
dest = dest->right;
217
Rahul Publications
B.Sc. II YEAR III SEMESTER
break; }
} else
} {
Node *target = dest; Node *smallest = target->right;
n s
if(target->rightThread && target->left
tio
} Thread)
{
/* using replace mode*/
dest->key = target->key;
l i c ap->right = target->right;
}
b p->rightThread =true;
Pu
}
if(p->key >= target->key)
{
ul elseif(target->rightThread)
{
ah
if(target->rightThread && target->left
Thread) Node *largest = target->left;
{
R
p->left = target->left;
while(!largest->rightThread)
{
largest = largest->right;
p->leftThread =true;
}
}
largest->right = target->right;
elseif(target->rightThread)
p->right = target->left;
{
}
Node *largest = target->left; else
while(!largest->rightThread) {
{ Node *smallest = target->right;
largest = largest->right; while(!smallest->leftThread)
} {
largest->right = p; smallest = smallest->left;
p->left = target->left; }
218
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
smallest->left = p; cout<<“\nThreadedBinarySearchTree
p->right = target->right; Operations\n”;
} cout<<“1. Insert “<<endl;
} cout<<“2. Delete”<<endl;
} cout<<“3. Search”<<endl;
/* Function to print tree */
cout<<“4. Clear”<<endl;
void printTree()
cout<<“Enter Your Choice: “;
{
Node *tmp = root, *p; cin>>choice;
for(;;) switch(choice)
{ {
p = tmp; case1:
tmp = tmp->right;
cout<<“Enter integer element to insert: “;
if(!p->rightThread)
{
cin>>val;
n s
tio
tbst.insert(val);
while(!tmp->leftThread)
break;
{
tmp = tmp->left;
l i c
case2:a
}
b cout<<“Enter integer element to delete: “;
}
if(tmp == root)
ul Pu cin>>val;
tbst.Delete(val);
ah
break;
break;
cout<<tmp->key<<“ “;
}
cout<<endl;
R case3:
cout<<“Enter integer element to search: “;
cin>>val;
}
}; if(tbst.search(val)==true)
/* Main Contains Menu */ cout<<“Element “<<val<<“ found in the
int main() tree”<<endl;
{ else
ThreadedBinarySearchTree tbst;
cout<<“Element “<<val<<“ not found in
cout<<“ThreadedBinarySearchTree Test\n”; the tree”<<endl;
char ch; break;
int choice, val;
case4:
/* Perform tree operations */
cout<<“\nTree Cleared\n”;
do
{ tbst.makeEmpty();
219
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
}
OUTPUT
ThreadedBinarySearchTree Test
l i c a
b
Pu
ThreadedBinarySearchTree Operations
Inorder traversal of expression tree produces
1. Insert
2. Delete
ul infix version of given postfix expression (same with
preorder traversal it gives prefix expression)
3. Search
4. Clear
R
Enter Your Choice: 1
ah Evaluating the expression represented by
expression tree:
Let t be the expression tree
If t is not null then
Enter integer element to insert: 28
If t.value is operand then
Tree = 28
Return t.value
Do you want to continue(Type y or n): y
A = solve(t.left)
ThreadedBinarySearchTree Operations
B = solve(t.right)
1. Insert
// calculate applies operator ‘t.value’
2. Delete
// on A and B, and returns value
3. Search
Return calculate(A, B, t.value)
4. Clear
Construction of Expression Tree:
Enter Your Choice: 1
Now For constructing expression tree we use a stack.
Enter integer element to insert: 5 We loop through input expression and do following
Tree = 528 for every character.
220
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
a file of n records, where each element is a key
number. The task is to find a particular key in the
tio
In decision analysis a decision tree and the list in the shortest possible time. If you know you
closely related influence diagram are used as a are going to search for an item in a set, you will
visual and analytical decision support tool, where
the expected values (or expected utility) of
l i c a
need to think carefully about what type of data
structure you will use for that set. At low level, the
competing alternatives are calculated.
u b
only searches that get mentioned are for sorted and
unsorted arrays. However, these are not the only
1.
ul P
A decision tree consists of 3 types of nodes:
Decision nodes - commonly represented by
data types that are useful for searching.
1. Linear search
ah
squares
Start at the beginning of the list and check
2. Chance nodes - represented by circles every element of the list. Very slow [order
3. R
End nodes - represented by triangles
Decision trees are commonly used
2.
O(n) ] but works on an unsorted list.
Binary Search
in operations research and operations manage- This is used for searching in a sorted array.
ment. If in practice decisions have to be taken online Test the middle element of the array. If it is
with no recall under incomplete knowledge, a too big. Repeat the process in the left half of
decision tree should be paralleled by a proba- the array, and the right half if it’s too small.
In this way, the amount of space that needs
bility model as a best choice model or online selecti-
to be searched is halved every time, so the
on model algorithm. Another use of decision trees
time is O(log n).
is as a descriptive means for calculating conditional
probabilities. 3. Hash Search
Decision trees, influence diagrams, utility Searching a hash table is easy and extremely
functions, and other decision analysis tools and fast, just find the hash value for the item you’re
looking for then go to that index and start
methods are taught to undergraduate students in
searching the array until you find what you
schools of business, health economics, and public
are looking for or you hit a blank spot. The
health, and are examples of operations research order is pretty close to o(1), depending on
or management science methods. how full your hash table is.
221
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a
Step 2: Compare, the search element with the first element in the list. tio
b l i
Step 3: If both are matching, then display “Given element found!!!” and terminate the function
u
Step 4: If both are not matching, then compare search element with the next element in the list.
P
ul
Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in the list.
h
Step 6: If the last element in the list is also doesn’t match, then display “Element not found!!!” and
a
terminate the function.
Example
R
Consider the following list of element and search element.
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
Search element 12
Step 1:
search element (12) is compared with first element (65)
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
12
222
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Step 2:
search element (12) is compared with next element (20)
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
12
Both are not matching. So move to next element
Step 3:
search element (12) is compared with next element (10)
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
12
c a tio
0 1 2
list 65 20 10
3 4 5
b
55 32 12l i 6 7
50 99
ul Pu 12
R ah
search element (12) is compared with next element (32)
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
12
0 1 2 3 4 5 6 7
list 65 20 10 55 32 12 50 99
12
both are matching. So we stop comparing and display element found at index 5.
223
Rahul Publications
B.Sc. II YEAR III SEMESTER
n
same process for left sublist of the middle element.
tio
cin>>x;
for(i=0;i<n;++i) If the search element is larger, then we repeat the
{
if(a[i]==x)
l i c a
same process for right sublist of the middle element.
We repeat this process until we find the search
u b
element in the list or until we left with a sublist of
only one element. And if that element also doesn’t
{ flag=1;
break;
}
}
if(flag)
R
cout<<“\nElement is found at position
“<<i+1;
Step 1: Read the search element from the
user
Step 2: Find the middle element in the
else sorted list
cout<<“\n Step 3: Compare, the search element with
Element not found”; the middle element in the sorted list.
return 0; Step 4: If both are matching, then display
} “Given element found!!!” and terminate the
function
Output
How many elements?4 Step 5: If both are not matching, then check
whether the search element is smaller or
Enter elements of the array larger than middle element.
5 9 12 4
Step 6: If the search element is smaller than
Enter element to search:9 middle element, then repeat steps 2, 3, 4 and
Element is found at position 2 5 for the left sublist of the middle element.
224
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Step 7: If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
Step 8: Repeat the same process until we find the search element in the list or until sublist contains
only one element.
Step 9: If that element also doesn’t match with the search element, then display “Element not
found in the list!!!” and terminate the function.
Example : Consider the following list of element and search element
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
search element 12
Step 1:
search element (12) is compared with middle element (SO)
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
n s
tio
12
ul P
20 32 50 55 65 80 99
Step 2:
a h
R
search element (12) is compared with middle element (12)
0 1
list 10 12
2 3 4 5 6 7 8
20 32 50 55 65 80 99
12
Both are matching. So the result is “Element found at index 1'
search element 80
Step 1:
search element (80) is compared with middle element (50)
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
80
225
Rahul Publications
B.Sc. II YEAR III SEMESTER
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
Step 2:
search element (80) is compared with middle element (65)
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
80
0 1 2 3 4 5 6 7 8
list 10 12 20 32 50 55 65 80 99
Step 3:
n s
tio
search element (80) is compared with middle element (80)
0 1 2 3 4 5 6 7 8
l i c a
list 10 12 20 32 50 55 65 80 99
b
Pu
80
ul
Both are not matching. So the result is “Element found at index 7”
ah
Q24. Write a program to implement binary search.
Ans :
R
Binary Search implementation
#include<iostream>
using namespace std;
int main()
{
int search(int [],int,int);
int n,i,a[100],e,res;
cout<<"How Many Elements:";
cin>>n;
cout<<"\nEnter Elements of Array in Ascending order\n";
for(i=0;i<n;++i)
{
226
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
cin>>e; Ans :
res=search(a,n,e); Sorting is a technique to rearrange the
if(res!=0) elements of a list in ascending or descending order,
which can be numerical, lexicographical, or any
cout<<"\nElement found at user-defined order. Sorting is a process through
position "<<res+1; which the data is arranged in ascending or
else descending order.
int f,l,m;
n s
time in memory is called internal sorting. There is a
limitation for internal sorts; they can only process
tio
f=0; relatively small lists due to memory constraints.
l=n-1;
while(f<=l)
l i c a
There are 3 types of internal sorts.
Selection sort
b Heap Sort
Pu
{
m=(f+l)/2; Insertion sort
u
if(e==a[m])
l Shell Sort algorithm
ah
return(m); Bubble Sort
Quick sort algorithm
R
else
if(e>a[m]) External Sorts: Sorting large amount of data
requires external or secondary memory. This process
f=m+1;
uses external memory such as HDD, to store the
else data which is not fit into the main memory. So,
l=m-1; primary memory holds the currently being sorted
data only. All external sorts are based on process of
}
merging. Different parts of data are sorted separately
return 0; and merged together. Ex: Merge Sort
} 3.2.2.1 Selection Sort
Output Q26. Explain Selection Sort with an example.
How Many Elements:5
Ans : (June-2018)
Enter Elements of Array in Ascending order
In selection sort, the smallest value among
12 39 40 68 77 the unsorted elements of the array is selected in
Enter element to search:40 every pass and inserted to its appropriate position
into the array. It is also the simplest algorithm. It is
Element found at position 3
an in-place comparison sorting algorithm. In this
227
Rahul Publications
B.Sc. II YEAR III SEMESTER
algorithm, the array is divided into two parts, first is sorted part, and another one is the unsorted part.
Initially, the sorted part of the array is empty, and unsorted part is the given array. Sorted part is placed at
the left, while the unsorted part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the first
position. After that second smallest element is selected and placed in the second position. The process
continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the number of items.
Due to this, it is not suitable for large data sets.
Algorithm
SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
s
Step 4: EXIT
SMALLEST (arr, i, n, pos)
Step 1: [INITIALIZE] SET SMALL = arr[i]
tio n
Step 2: [INITIALIZE] SET pos = i
l i c a
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
u b
SET SMALL = arr[j]
SET pos = j
ul P
[END OF if]
a h
[END OF LOOP]
R
Step 4: RETURN pos
Working of Selection sort Algorithm
To understand the working of the Selection sort algorithm, let’s take an unsorted array. It will be
easier to understand the Selection sort via an example.
Let the elements of array are:
12 29 25 8 32 17 40
Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.
12 29 25 8 32 17 40
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
228
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
8 29 25 12 32 17 40
For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array that
should be appeared at second position.
8 29 25 12 32 17 40
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted
array. So, after two iterations, the two smallest values are placed at the beginning in a sorted way.
8 12 25 29 32 17 40
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
8 12 25 29 32 17 40
s
8 12 25 29 32 17 40
8 12 17 29 32 25 40
tio n
8 12 17 29 32 25 40
l i c a
8 12 17
b
29 32 25 40
ul
8
8
12 17
12 17
Pu 25 32 29 40
25 32 29 40
R ah 8
8
12 17
12 17
25 32 29 40
25 29 32 40
8 12 17 25 29 32 40
Now, the array is completely sorted.
Complexity Analysis of Selection Sorting
Worst Case Time Complexity : O(n2)
Best Case Time Complexity : O(n2)
Average Time Complexity : O(n2)
Space Complexity : O(1)
Q27. Write a program to implement selection sort
Ans : (June-18)
Implementation of selection sort
#include<iostream>
229
Rahul Publications
B.Sc. II YEAR III SEMESTER
b
given array elements.
Pu
if(min>a[j])
begin BubbleSort(arr)
{
ul
min=a[j];
for all array elements
if arr[i] > arr[i+1]
ah
loc=j;
swap(arr[i], arr[i+1])
}
temp=a[i];
R }
end if
end for
return arr
a[i]=a[loc];
end BubbleSort
a[loc]=temp;
Working of Bubble sort Algorithm
}
To understand the working of bubble sort
algorithm, let’s take an unsorted array. We are taking
cout<<“\nSorted list is as follows\n”; a short and accurate array, as we know the
for(i=0;i<n;i++) complexity of bubble sort is O(n2).
{ Let the elements of array are:
cout<<a[i]<<“ “; 13 32 26 35 10
}
First Pass
return 0;
Sorting will start from the initial two elements.
} Let compare them to check which is greater.
230
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
13 32 26 35 10 Third Pass
The same process will be followed for third
Here, 32 is greater than 13 (32 > 13), so it is iteration.
already sorted. Now, compare 32 with 26.
13 26 10 32 35
13 32 26 35 10
13 26 10 32 35
Here, 26 is smaller than 36. So, swapping is
required. After swapping new array will look
Here, 10 is smaller than 26. So, swapping is
like -
required. After swapping, the array will be:
13 26 32 35 10 13 10 26 32 35
13 26 32 35 10 13 10 26 32 35
tio
and 10. will be
13 26 32 35 10
l i c a 10 13 26 32 35
u
sorted. So, swapping is required. Now, we b Hence, there is no swapping required, so the
array is completely sorted.
ul P
reach at the end of the array. After first pass, Time Complexity
Case Time Complexity
13
R ah
26 32 10 35
231
Rahul Publications
B.Sc. II YEAR III SEMESTER
a[j+1] = temp;
flag = 1; //setting flag as 1, if swapping occurs
} }
if(!flag) //breaking out of for loop if no swapping takes place
{
break;
}}
3.2.2.3 Insertion Sort
Q29. What is insertion sort? Explain its working with an example.
n s
The same approach is applied in insertion sort. The idea behind the insertion sort is that first take
tio
one element, iterate it through the sorted array. Although it is simple to use, it is not appropriate for large
a
data sets as the time complexity of insertion sort in the average case and worst case is O(n2), where n is
c
the number of items. Insertion sort is less efficient than the other sorting algorithms like heap sort, quick
sort, merge sort, etc.
l i
u
Insertion sort has various advantages such as:
b
Simple implementation
Efficient for small data sets
ul P
a h
Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Algorithm
Step 1:
R
The simple steps of achieving the insertion sort are listed as follows:
If the element is the first element, assume that it is already sorted. Return 1.
Step2: Pick the next element, and store it separately in a key.
Step3: Now, compare the key with all elements in the sorted array.
Step 4: If the element in the sorted array is smaller than the current element, then move to the next
element. Else, shift greater elements in the array towards the right.
Step 5: Insert the value.
Step 6: Repeat until the array is sorted.
Working of Insertion sort Algorithm
To understand the working of the insertion sort algorithm, let’s take an unsorted array. It will be
easier to understand the insertion sort via an example.
Let the elements of array are:
232
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
12 31 25 8 32 17
Initially, the first two elements are compared in insertion sort.
12 31 25 8 32 17
Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12 is
stored in a sorted sub-array.
12 31 25 8 32 17
Now, move to the next two elements and compare them.
12 31 25 8 32 17
12 31 25 8 32 17
Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25. Along with
swapping, insertion sort will also check it with all elements in the sorted array.
For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the
sorted array remains sorted after swapping.
n s
tio
12 25 31 8 32 17
31 and 8.
l i a
Now, two elements in the sorted array are 12 and 25. Move forward to the next elements that are
c
12 25 31 8
b 32 17
l
12
Pu
25 31 8
Both 31 and 8 are not sorted. So, swap them.
u
32 17
R ah 12 25 8
12 25 8 31 32 17
12 8 25 31 32 17
12 8 25 31 32 17
8 12 25 31 32 17
Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that are 31 and 32.
8 12 25 31 32 17
233
Rahul Publications
B.Sc. II YEAR III SEMESTER
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.
8 12 25 31 32 17
8 12 25 31 32 17
8 12 25 31 17 32
8 12 25 31 17 32
8 12 25 17 31 32
8 12 25 17 31 32
n s
tio
8 12 17 25 31 32
l i c a
Time Complexity
Best Case O(n)
u b
Average Case
Worst Case
O(n2)
O(n2)
ul P
a h
Q30. Write a program to implement Insertion sort.
Ans :
R
Insertion Sorting in C++
#include <stdlib.h>
#include <iostream.h>
using namespace std;
//member functions declaration
void insertionSort(int arr[], int length);
void printArray(int array[],int size);
int main() {
int array[5]= {5,4,3,2,1};
insertionSort(array,5);
return 0;
}
234
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
void insertionSort(int arr[], int length) { into two equal halves, calls itself for the two halves
int i, j ,tmp; and then merges the two sorted halves. We have to
define the merge() function to perform the
for (i = 1; i < length; i++) { merging.
j = i; The sub-lists are divided again and again into
while (j > 0 && arr[j - 1] > arr[j]) { halves until the list cannot be divided further. Then
we combine the pair of one element lists into two-
tmp = arr[j];
element lists, sorting them in the process. The sorted
arr[j] = arr[j - 1]; two-element pairs is merged into the four-element
lists, and so on until we get the sorted list.
arr[j - 1] = tmp;
Algorithm
j—;
} In the following algorithm, arr is the given
array, beg is the starting element, and end is the
printArray(arr,5); last element of the array.
}} MERGE_SORT(arr, beg, end)
void printArray(int array[], int size){ if beg < end
n s
tio
cout<< “Sorting tha array using Insertion set mid = (beg + end)/2
sort... “;
int j;
l i a
MERGE_SORT(arr, beg, mid)
c
MERGE_SORT(arr, mid + 1, end)
for (j=0; j < size;j++)
for (j=0; j < size;j++)
u b MERGE (arr, beg, mid, end)
ul
cout <<“ “<< array[j];
P end of if
END MERGE_SORT
ah
cout << endl;
The important part of the merge sort is
}
R
Complexity Analysis of Insertion Sorting
Worst Case Time Complexity : O(n2)
the MERGE function. This function performs the
merging of two sorted sub-arrays that
are A[beg…mid] and A[mid+1…end], to build
one sorted array A[beg…end]. So, the inputs of
Best Case Time Complexity : O(n) the MERGE function are A[], beg, mid, and end.
Average Time Complexity : O(n2) The implementation of the MERGE function
Space Complexity : O(1) is given as follows:
235
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
while(i <= q && j <= r)
3.2.2.5 Quick Sort
n s
sorting Linked Lists.
{
if(a[i] < a[j])
c a
example? tio
Q32. What is quick sort? Explain it with an
b[k++] = a[i++];
// same as b[k]=a[i]; k++; i++;
Ans :
b l i (July-2019)
Pu
} Sorting is a way of arranging items in a
systematic manner. Quicksort is the widely used
else
{
ul sorting algorithm that makes n log n comparisons
ah
in average case for sorting an array of n elements.
b[k++] = a[j++]; It is a faster and highly efficient sorting algorithm.
} }
while(i <= q)
{
R This algorithm follows the divide and conquer
approach. Divide and conquer is a technique of
breaking down the algorithms into subproblems,
then solving the subproblems, and combining the
b[k++] = a[i++];
results back together to solve the original problem.
}
while(j <= r) Divide
{ In Divide, first pick a pivot element. After that,
b[k++] = a[j++]; partition or rearrange the array into two sub-arrays
} such that each element in the left sub-array is less
for(i=r; i >= p; i—) than or equal to the pivot element and each element
{ in the right sub-array is larger than the pivot
a[i] = b[—k]; element.
// copying back the sorted list to a[] Conquer
} Recursively, sort two subarrays with
} Quicksort.
236
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
Combine the already sorted array. The partition algorithm rearranges the sub-
arrays in a place.
Quicksort picks an element as pivot, and then
it partitions the given array around the picked pivot PARTITION (array A, start, end)
element. In quick sort, a large array is divided into {
two arrays in which one holds values that are smaller pivot ? A[end]
than the specified value (Pivot), and another array
i ? start-1
holds the values that are greater than the pivot.
for j ? start to end -1 {
After that, left and right sub-arrays are also
partitioned using the same approach. It will continue do if (A[j] < pivot) {
until the single element remains in the sub-array. then i ? i + 1
Quick Sort swap A[i] with A[j]
}}
swap A[i+1] with A[end]
n s
tio
return i+1
l
}
i c a
Working of Quick Sort Algorithm
u
Picking a good pivot is necessary for the fast
b To understand the working of quick sort, let’s
take an unsorted array. It will make the concept
P
implementation of quicksort. However, it is typical
ul
to determine a good pivot. Some of the ways of
choosing a pivot are as follows:
more clear and understandable.
Let the elements of array are:
a h
Pivot can be random, i.e. select the random
R
pivot from the given array.
Pivot can either be the rightmost element of
the leftmost element of the given array.
24 9 29 14 19 27
237
Rahul Publications
B.Sc. II YEAR III SEMESTER
pivot Right
19 9 24 14 29 27
Now, a[left] = 24, a[right] = 19, and a[pivot]
= 24.
Left Right
Because, a[pivot] > a[right], so, algorithm will
swap a[pivot] with a[right], and pivot moves Since, pivot is at left, so algorithm starts from
to right, as - right, and move to left. Now, a[left] = 24,
a[right] = 29, and a[pivot] = 24. As a[pivot]
pivot < a[right], so algorithm moves one position
to left, as -
pivot
19 9 29 14 24 27
n s
Left Right 19
c a
9
tio24 14 29 27
b l i Left Right
Pu
starts from left and moves to right.
Now, a[pivot] = 24, a[left] = 24, and a[right]
As a[pivot] > a[left], so algorithm moves one = 14. As a[pivot] > a[right], so, swap a[pivot]
position to right as -
19 9
R 29
ah
14
pivot
24 27 19 9 14
pivot
24 29 27
Now, a[left] = 9, a[right] = 24, and a[pivot] Now, a[pivot] = 24, a[left] = 14, and a[right]
= 24. As a[pivot] > a[left], so algorithm = 24. Pivot is at right, so the algorithm starts
moves one position to right as - from left and move to right.
pivot pivot
19 9 24 14 29 27 19 9 14 24 29 27
Left Right
Left Right
238
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
tio
swap(&a[h],&a[pvt]);
9 14 19 24 27 29
• Time Complexity
l
}
i c a
returnPartition(a, l, h);
ul Pu int pindex;
if(l < h){
ah
Q33. Write a program to implement quick pindex =RandomPivotPartition(a, l, h);
sort.
Ans :
#include<iostream>
R QuickSort(a, l, pindex-1);
QuickSort(a, pindex+1, h);
}
#include<cstdlib> return0;
usingnamespace std; }
void swap(int*a,int*b){ int main(){
int temp; int n, i;
temp =*a; cout<<"\nEnter the number of data element
*a =*b; to be sorted: ";
*b = temp; cin>>n;
} int arr[n];
intPartition(int a[],int l,int h){ for(i =0; i < n; i++){
int pivot, index, i; cout<<"Enter element "<<i+1<<": ";
index = l; cin>>arr[i];
239
Rahul Publications
B.Sc. II YEAR III SEMESTER
} Pros
QuickSort(arr,0, n-1); Again nothing, maybe just “catchy name1”
cout<<"\nSorted Data "; Cons
for(i =0; i < n; i++) With polynomial O(n2) it is too slow
cout<<"->"<<arr[i]; Insertion sort
return0; Insertion sort is definitely not the most efficient
} algorithm out there but its power lies in its simplicity.
Since it is very easy to implement and adequately
Output efficient for small number of elements, it is useful
Enter the number of data element to be for small applications or trivial ones. The definition
sorted: 4 Enter element 1: 3 of small is vague and depends on a lot of things but
a safe bet is if under 50, insertion sort is fast enough.
Enter element 2: 4 Another situation that insertion sort is useful is when
Enter element 3: 7 the sequence is almost sorted. Such sequences may
seem like exceptions but in real world applications
Enter element 4: 6 often you encounter almost sorted elements. The
Sorted Data ->3->4->6->7
n s
run time of insertions sort is O(n2) at worst case
scenario. So far we have another useless alternative
tio
3.2.3 Comparison of All Sorting Methods for selection sort. But if implemented well the run
Q34. Compare various sorting techniques
with real world usage.
c a
time can be reduced to O(n+k). n is the number of
elements and k is the number of inversions (the
l i
number of pair of elements out of order). With this
Ans : (July-21, Nov.-2019)
u b
new run time in mind you can see if the sequence is
almost sorted (k is small) the run time can be almost
Selection sort
ul P
Selection sort is an exception in our list. This
linear which is a huge improvement over the
polynomial n2.
a h
is considered an academic sorting algorithm.
Because the time efficiency is always O(n2) which is
Pros
R
not acceptable. There is no real world usage for
selection sort except passing the data structure course
exam.
Easy to implement
The more the sequence is ordered the closer
is run time to linear time O(n)
Pros Cons
Nothing Not suitable for large data sets
cons Still polynomial at worst case
2
Always run at O(n ) even at best case scenario
Heap sort
Bubble sort
This is the first general purpose sorting
This is the other exception in the list because algorithm we are introducing here. Heap sort runs
bubble sort is too slow to be practical. Unless the at O(nlogn) which is optimal for comparison based
sequence is almost sorted feasibility of bubble sort sorting algorithms. Though heap sort has the same
is zero and the running time is O(n2). This is one of run time as quick sort and merge sort but it is usually
the three simple sorting algorithms alongside outperformed in real world scenarios. If you are
selection sort and insertion sort but like selection asking then why should anyone use it, the answer
sort falls short of insertions sort in terms of efficiency lies in space efficiency. Nowadays computers come
even for small sequences. with huge amount of memory, enough for many
240
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
applications. Does this mean heap sort is losing its shine? No, still when writing programs for environments
with limited memory, such as embedded systems or space efficiency is much more important than time
efficiency. A rule of thumb is if the sequence is small enough to easily fit in main memory then heap sort
is good choice.
Pros
Runs at O(nlogn)
Can be easily implemented to be executed in place
Cons
Not as fast as other comparison based algorithms in large data sets
It doesn’t provide stable sorting
Quick sort
One of the most widely used sorting algorithms in computer industry. Surprisingly quick sort has a
running time of O(n2) that makes it susceptible in real-time applications. Having a polynomial worst case
scenario still quick sort usually outperforms both quick sort and merge sort (coming next). The reason
behind the popularity of quick sort despite the short comings is both being fast in real world scenarios (not
s
necessarily worst case) and the ability to be implemented as an in place algorithm.
n
tio
Pros
Most often than not runs at O(nlogn)
i c a
Quick sort is tried and true, has been used for many years in industry so you can be assured it is not
going to fail you
l
u
High space efficiency by executing in place
b
Cons
ul P
Polynomial worst case scenario makes it susceptible for time critical applications
a h
Provides non stable sort due to swapping of elements in partitioning step
Merge sort
R
Having a O(nlogn) worst case scenario run time makes merge sort a powerful sorting algorithm.
The main drawback of this algorithm is its space inefficiency. That is in the process of sorting lots of
temporary arrays have to be created and many copying of elements is involved. This doesn’t mean merge
sort is not useful. When the data to be sorted is distributed across different locations like cache, main
memory etc then copying data is inevitable. Merge sort mainly owes its popularity to Tim Peters who
designed a variant of it which is in essence a bottom-up merge sort and is known as Tim sort.
Pros
Excellent choice when data is fetched from resources other than main memory
Having a worst case scenario run time of O(nlogn) which is optimal
Tim sort variant is really powerful
Cons
Lots of overhead in copying data between arrays and making new arrays
Extremely difficult to implement it in place for arrays
Space inefficiency
241
Rahul Publications
B.Sc. II YEAR III SEMESTER
worst case time average case time best case time worst case space
Selection sort O(n2 ) O(n2 ) O(n2 )
o n s O(n)
Bubble sort O(n2 ) O(n2 )
t i
O(n) O(1)
ca
Insertion sort O(n2 ) O(n2 ) O(n) O(n)
Heap sort O(nlogn)
l
O(nlogn)
i O(nlogn) O(1)
ub
Quick sort O(n2 ) O(nlogn) O(nlogn) O(logn)
Merge sort
ul P
O(nlogn) O(nlogn) O(nlogn) O(n)
R
Q35. What is symbol table? How to represent it?
Ans :
Symbol Table
The symbol table is a kind of a ‘keyed table’ which stores <key, information> pairs with no additional
logical structure.
The operations performed on symbol tables are the following:
1. Inserting the <key, information> pairs into the collection.
2. Removing the <key, information> pairs by specifying the key.
3. Searching for a particular key.
4. Retrieving the information associated with a key.
Representation of Symbol Table
There are two different techniques for implementing a keyed table, namely, the symbol table and
the tree table.
242
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
l i
We know the key values of each node in the tree, and we also know the frequencies of each node
b
P u
in terms of searching means how much time is required to search a node. The frequency and key-value
determine the overall cost of searching a node. The cost of searching is a very important factor in various
ul
applications. The overall cost of searching a node should be less. The time required to search a node in
BST is more than the balanced binary search tree as a balanced binary search tree contains a lesser
a h
number of levels than the BST. There is one way that can reduce the cost of a binary search treeis known
as an optimal binary search tree.
R
Let’s understand through an example.
If the keys are 10, 20, 30, 40, 50, 60, 70
In the above tree, all the nodes on the left subtree are smaller than the value of the root node, and
all the nodes on the right subtree are larger than the value of the root node. The maximum time required
to search a node is equal to the minimum height of the tree, equal to logn.
243
Rahul Publications
B.Sc. II YEAR III SEMESTER
Now we will see how many binary search trees In the above tree, the average number of
can be made from the given number of keys. comparisons that can be made as:
For example: 10, 20, 30 are the keys, and Average number of comparisons
the following are the binary search trees that can
1 2 3
be made out from these keys. = =2
3
The Formula for calculating the number of
trees:
2n
Cn
n 1
When we use the above formula, then it is
found that total 5 number of trees can be created.
The cost required for searching an element
depends on the comparisons to be made to search
an element. Now, we will calculate the average cost Average number of comparisons
of time of the above binary search trees. 1 2 2
= =5/3
3
n s
c a tio
b l i
P u
ul
In the above tree, total number of 3
comparisons can be made. The average number of
a h
comparisons can be made as: In the above tree, the total number of
comparisons can be made as 3. Therefore, the
=
R
Average number of comparisons
1 2 3
3
=2
average number of comparisons that can be made
as:
Average number of comparisons
1 2 2
= =2
3
244
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
1 2 2
Average number of comparisons = =2
3
In the third case, the number of comparisons is less because the height of the tree is less, so it’s a
balanced binary search tree.
Till now, we read about the height-balanced binary search tree. To find the optimal binary search
tree, we will determine the frequency of searching a key.
Let’s assume that frequencies associated with the keys 10, 20, 30 are 3, 2, 5.
The above trees have different frequencies. The tree with the lowest frequency would be considered
the optimal binary search tree. The tree with the frequency 17 is the lowest, so it would be considered as
the optimal binary search tree.
Dynamic Approach
Consider the below table, which contains the keys and frequencies.
n s
c a tio
b l i
u
First, we will calculate the values where j-i is equal to zero.
P
ul
When i=0, j=0, then j-i = 0
h
When i = 1, j=1, then j-i = 0
R a
When i = 2, j=2, then j-i = 0
When i = 3, j=3, then j-i = 0
When i = 4, j=4, then j-i = 0
Therefore, c[0, 0] = 0, c[1 , 1] = 0, c[2,2] = 0, c[3,3] = 0, c[4,4] = 0
Now we will calculate the values where j-i equal to 1.
When j=1, i=0 then j-i = 1
When j=2, i=1 then j-i = 1
When j=3, i=2 then j-i = 1
When j=4, i=3 then j-i = 1
Now to calculate the cost, we will consider only the jth value.
The cost of c[0,1] is 4 (The key is 10, and the cost corresponding to key 10 is 4).
The cost of c[1,2] is 2 (The key is 20, and the cost corresponding to key 20 is 2).
The cost of c[2,3] is 6 (The key is 30, and the cost corresponding to key 30 is 6)
The cost of c[3,4] is 3 (The key is 40, and the cost corresponding to key 40 is 3)
245
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
The minimum cost is 12,
tio
There are two possible trees that can be made therefore, c[2,4] = 12
out from these two keys shown below:
l i c a
u b
ul P
a h
In the first binary tree, cost would be: 4*1 +
R
2*2 = 8
In the second binary tree, cost would be: 4*2
+ 2*1 = 10 Now we will calculate the values when j-i = 3
The minimum cost is 8; therefore, c[0,2] = 8 When j=3, i=0 then j-i = 3
When j=4, i=1 then j-i = 3
When i=0, j=3 then we will consider three
keys, i.e., 10, 20, and 30.
The following are the trees that can be made
if 10 is considered as a root node.
246
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
In the above tree, 10 is the root node, 20 is the right child of node 10, and 30 is the right child of
node 20.
In the above tree, 10 is the root node, 30 is the right child of node 10, and 20 is the left child of
node 20.
n s
c a tio
b l i
node 20.
P u
In the above tree, 20 is the root node, 30 is the right child of node 20, and 10 is the left child of
a h ul
Cost would be: 1*2 + 4*2 + 6*2 = 22
The following are the trees that can be created if 30 is considered as the root node.
R
In the above tree, 30 is the root node, 20 is the left child of node 30, and 10 is the left child of node
20.
247
Rahul Publications
B.Sc. II YEAR III SEMESTER
In the above tree, 30 is the root node, 10 is the left child of node 30 and 20 is the right child of node
10.
Cost would be: 1*6 + 2*4 + 3*2 = 20
Therefore, the minimum cost is 20 which is the 3rd root. So, c[0,3] is equal to 20.
When i=1 and j=4 then we will consider the keys 20, 30, 40
c[1,4] = min{ c[1,1] + c[2,4], c[1,2] + c[3,4], c[1,3] + c[4,4] } + 11
= min{0+12, 2+3, 10+0}+ 11
= min{12, 5, 10} + 11
The minimum value is 5; therefore, c[1,4] = 5+11 = 16
n s
Now we will calculate the values when j-i = 4
c a tio
When j=4 and i=0 then j-i = 4
b l i
In this case, we will consider four keys, i.e., 10, 20, 30 and 40. The frequencies of 10, 20, 30 and
40 are 4, 2, 6 and 3 respectively.
P u
ul
w[0, 4] = 4 + 2 + 6 + 3 = 15
a h
If we consider 10 as the root node then
C[0, 4] = min {c[0,0] + c[1,4]}+ w[0,4]= min {0 + 16} + 15= 31
R
If we consider 20 as the root node then
C[0,4] = min{c[0,1] + c[2,4]} + w[0,4]= min{4 + 12} + 15= 16 + 15 = 31
If we consider 30 as the root node then,
C[0,4] = min{c[0,2] + c[3,4]} +w[0,4] = min {8 + 3} + 15 = 26
If we consider 40 as the root node then,
C[0,4] = min{c[0,3] + c[4,4]} + w[0,4]= min{20 + 0} + 15= 35
In the above cases, we have observed that 26 is the minimum cost; therefore, c[0,4] is equal to 26.
248
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
ul P
Balance factor of a node is the difference between the heights of left and right subtrees of that node.
The balance factor of a node is calculated either height of left subtree - height of right subtree (OR) height
h
of right subtree - height of left subtree. In the following explanation, we are calculating as follows...
a
R
Balance factor = heightOfLeftSubtree – height Of RightSubtree
Example
The above tree is a binary search tree and every node is satisfying balance factor condition. So this
tree is said to be an AVL tree.
Every AVL Tree is a binary search tree but all the Binary Search Trees need not to be AVL trees.
249
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Single Left Rotation (LL Rotation)
c a tio
l i
In LL Rotation every node moves one position to left from the current position. To understand LL
Rotation, let us consider following insertion operations into an AVL Tree.
b
P u
a h ul
R
Single Right Rotation (RR Rotation)
In RR Rotation every node moves one position to right from the current position. To understand
RR Rotation, let us consider following insertion operations into an AVL Tree.
250
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
n s
c a tio
b l i
P u
a h ul
Q38. Explain the operations on an AVL tree with an example.
Ans :
R
Operations on an AVL Tree
The following operations are performed on an AVL tree.
1. Search
2. Insertion
3. Deletion
Search Operation in AVL Tree
In an AVL tree, the search operation is performed with O(log n) time complexity. The search
operation is performed similar to Binary search tree search operation. We use the following steps to search
an element in AVL tree..
Step 1: Read the search element from the user
Step 2: Compare, the search element with the value of root node in the tree.
Step 3: If both are matching, then display “Given node found!!!” and terminate the function
Step 4: If both are not matching, then check whether search element is smaller or larger than that
node value.
251
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step 5: If search element is smaller, then continue the search process in left subtree.
Step 6: If search element is larger, then continue the search process in right subtree.
Step 7: Repeat the same until we found exact element or we completed with a leaf node
Step 8: If we reach to the node with search value, then display “Element is found” and terminate
the function.
Step 9: If we reach to a leaf node and it is also not matching, then display “Element not found”
and terminate the function.
Insertion Operation in AVL Tree
In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL Tree,
new node is always inserted as a leaf node. The insertion operation is performed as follows..
Step 1: Insert the new element into the tree using Binary Search Tree insertion logic.
Step 2: After insertion, check the Balance Factor of every node.
Step 3: If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 4: If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
s
imbalanced. Then perform the suitable Rotation to make it balanced. And go for next operation.
n
tio
Example: Construct an AVL Tree by inserting numbers from 1 to 8.
insert 1
0
1 l i c a
Tree is balanced
u b
inset 2
ul P
a h
Tree is balanced
R
insert 3
After LL Rotation
insert 4
Tree is balanced
252
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
insert 5
insert 6
After LL Rotation at 2
n s
Tree is imbalanced LL Rotation at 2
c a tio
Tree is balanced
b l i
Insert 7
P u
ul
After Rotation at 5
a h
RTree is Imbalanced LL Rotation at 5 Tree is balanced
insert 8
Tree is balanced
Deletion Operation in AVL Tree
In an AVL Tree, the deletion operation is similar to deletion operation in BST. But after every
deletion operation we need to check with the Balance Factor condition. If the tree is balanced after
deletion then go for next operation otherwise perform the suitable rotation to make the tree Balanced.
253
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
#include <iostream.h>
#include <stdlib.h>
#include<constream.h>
#define FALSE 0
#define TRUE 1
struct AVLNode
{
int data ;
int balfact ;
AVLNode *left ;
AVLNode *right ;
};
class avltree
n s
tio
{
private :
AVLNode *root ;
l i c a
public :
avltree( ) ;
u b
ul P
AVLNode* insert ( int data, int *h ) ;
static AVLNode* buildtree ( AVLNode *root, int data, int *h ) ;
a h
void display( AVLNode *root ) ;
AVLNode* deldata ( AVLNode* root, int data, int *h ) ;
R
static AVLNode* del ( AVLNode *node, AVLNode* root, int *h ) ;
static AVLNode* balright ( AVLNode *root, int *h ) ;
static AVLNode* balleft ( AVLNode* root, int *h ) ;
void setroot ( AVLNode *avl ) ;
~avltree( ) ;
static void deltree ( AVLNode *root ) ;
};
avltree :: avltree( )
{
root = NULL ;
}
AVLNode* avltree :: insert ( int data, int *h )
{
root = buildtree ( root, data, h ) ;
return root ;
254
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
}
AVLNode* avltree :: buildtree ( AVLNode *root, int data, int *h )
{
AVLNode *node1, *node2 ;
if ( root == NULL )
{
root = new AVLNode ;
root -> data = data ;
root -> left = NULL ;
root -> right = NULL ;
root -> balfact = 0 ;
*h = TRUE ;
return ( root ) ;
}
if ( data < root -> data )
n s
tio
{
root -> left = buildtree ( root -> left, data, h ) ;
u b
{
ul P
switch ( root -> balfact )
{
a h
case 1 :
255
Rahul Publications
B.Sc. II YEAR III SEMESTER
case 0 :
n s
root -> balfact = 1 ;
break ;
c a tio
case -1 :
root -> balfact = 0 ;
b l i
u
*h = FALSE ;
P
ul
}
}
}
a h
R
if ( data > root -> data )
{
root -> right = buildtree ( root -> right, data, h ) ;
if ( *h )
{
switch ( root -> balfact )
{
case 1 :
root -> balfact = 0 ;
*h = FALSE ;
break ;
case 0 :
root -> balfact = -1 ;
256
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
break ;
case -1 :
node1 = root -> right ;
if ( node1 -> balfact == -1 )
{
cout << “\nLeft rotation.” ;
root -> right = node1 -> left ;
node1 -> left = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
cout << “\nDouble rotation, right then left.” ;
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
n s
root -> right = node2 -> left ;
node2 -> left = root ;
c a tio
l i
if ( node2 -> balfact == -1 )
b
root -> balfact = 1 ;
else
P u
ul
root -> balfact = 0 ;
if ( node2 -> balfact == 1 )
R else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
return ( root ) ;
}
void avltree :: display ( AVLNode* root )
{
if ( root != NULL )
{
257
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
l i
root -> left = deldata ( root -> left, data, h ) ;
if ( *h )
b
u
root = balright ( root, h ) ;
P
ul
}
else
{
a h
{ R
if ( data > root -> data )
258
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
else
{
if ( node -> left == NULL )
{
root = node -> right ;
*h = TRUE ;
delete ( node ) ;
}
else
{
node -> right = del ( node -> right, node, h ) ;
if ( *h )
root = balleft ( root, h ) ;
}
}
}
}
n s
}
return ( root ) ;
c a tio
}
b l
AVLNode* avltree :: del ( AVLNode *succ, AVLNode *node, int *h ) i
{
P u
ul
AVLNode *temp = succ ;
a h
if ( succ -> left != NULL )
{
R
succ -> left = del ( succ -> left, node, h ) ;
if ( *h )
succ = balright ( succ, h ) ;
}
else
{
temp = succ ;
node -> data = succ -> data ;
succ = succ -> right ;
delete ( temp ) ;
*h = TRUE ;
}
return ( succ ) ;
}
259
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
if ( temp1 -> balfact == 0 )
{
b l i
u
root -> balfact = -1 ;
P
ul
temp1 -> balfact = 1 ;
*h = FALSE ;
}
a h
Relse
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else
{
cout << “\nDouble rotation, right then left.” ;
temp2 = temp1 -> left ;
temp1 -> left = temp2 -> right ;
temp2 -> right = temp1 ;
root -> right = temp2 -> left ;
temp2 -> left = root ;
if ( temp2 -> balfact == -1 )
260
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
c a tio
root -> balfact = 0 ;
break ;
b l i
P u
ul
case 0 :
root -> balfact = 1 ;
a h
*h = FALSE ;
R
break ;
case 1 :
temp1 = root -> left ;
if ( temp1 -> balfact >= 0 )
{
cout << “\nRight rotation.” ;
root -> left = temp1 -> right ;
temp1 -> right = root ;
261
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
else
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else
{
cout << “\nDouble rotation, left then right.” ;
temp2 = temp1 -> right ;
temp1 -> right = temp2 -> left ;
temp2 -> left = temp1 ;
root -> left = temp2 -> right ;
temp2 -> right = root ;
if ( temp2 -> balfact == 1 )
root -> balfact = -1 ;
n s
else
root -> balfact = 0 ;
c a tio
if ( temp2-> balfact == -1 )
temp1 -> balfact = 1 ;
b l i
else
P u
ul
temp1 -> balfact = 0 ;
root = temp2 ;
}
}
R
return ( root ) ;
}
void avltree :: setroot ( AVLNode *avl )
{
root = avl ;
}
avltree :: ~avltree( )
{
deltree ( root ) ;
}
void avltree :: deltree ( AVLNode *root )
{
if ( root != NULL )
262
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
c a tio
at.setroot ( avl ) ;
avl = at.insert ( 12, &h ) ;
b l i
at.setroot ( avl ) ;
P u
ul
avl = at.insert ( 25, &h ) ;
at.setroot ( avl ) ;
a h
avl = at.insert ( 32, &h ) ;
R
at.setroot ( avl ) ;
avl = at.insert ( 10, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 15, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 27, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 13, &h ) ;
at.setroot ( avl ) ;
cout << endl << “AVL tree:\n” ;
at.display ( avl ) ;
avl = at.deldata ( avl, 20, &h ) ;
at.setroot ( avl ) ;
avl = at.deldata ( avl, 12, &h ) ;
at.setroot ( avl ) ;
263
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
void inorder(tree_node *);
tio
void postordertrav();
void postorder(tree_node *);
l i c a
void preordertrav();
void preorder(tree_node *);
u
};
b
ul P void bst::insert(int item)
{
tree_node *p=new tree_node;
2.
a h
Write a C++ program for creation and
traversal of a Binary Tree
tree_node *parent;
Ans :
#include<iostream.h>
R p->data=item;
p->left=NULL;
p->right=NULL;
parent=NULL;
#include<conio.h>
if(isempty())
#include<process.h> root=p;
struct tree_node else
{ {
tree_node *left; tree_node *ptr;
ptr=root;
tree_node *right;
while(ptr!=NULL)
int data; {
}; parent=ptr;
class bst if(item>ptr->data)
{ ptr=ptr->right;
264
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
else if(ptr!=NULL)
ptr=ptr->left; {
} cout<<“ “<<ptr->data<<“ “;
if(item<parent->data) preorder(ptr->left);
parent->left=p; preorder(ptr->right);
else }
parent->right=p; }
} void main()
} {
void bst::inordertrav() bst b;
{ b.insert(52);
inorder(root); b.insert(25);
} b.insert(50);
void bst::inorder(tree_node *ptr) b.insert(15);
{ b.insert(40);
if(ptr!=NULL)
{
b.insert(45);
n s
tio
b.insert(20); cout<<“inorder”<<endl;
inorder(ptr->left); b.inordertrav();
cout<<“ “<<ptr->data<<“
inorder(ptr->right);
“;
c a
cout<<endl<<“postorder”<<endl;
l i
b.postordertrav();
}
}
u b cout<<endl<<“preorder”<<endl;
void bst::postordertrav()
{
ul P b.preordertrav();
getch();
postorder(root);
a h }
3. Explain ADT of Binary Tree
}
R
void bst::postorder(tree_node *ptr)
{
Ans :
A binary tree consists of nodes with one
if(ptr!=NULL) predecessor and at most two successors (called the
{ left child and the right child). The only exception is
the root node of the tree that does not have a
postorder(ptr->left);
predecessor. A node can contain any amount and
postorder(ptr->right); any type of data.
cout<<“ “<<ptr->data<<“ “;
1. create: A binary tree may be created in
}
several states. The most common include.
}
an empty tree (i.e. no nodes) and hence
void bst::preordertrav() the constructor will have no parameters
{
a tree with one node (i.e. the root) and
preorder(root); hence the constructor will have a single
} parameter (the data for the root node)
void bst::preorder(tree_node *ptr) a tree with a new root whose children
{ are other existing trees and hence the
265
Rahul Publications
B.Sc. II YEAR III SEMESTER
n
tio
unsorted arrays. However, these are not the only
nearly balanced.
data types that are useful for searching.
5. remove(): Removes the root node of the tree
and returns its data. The actual imple-
mentation of this method and other forms of
1.
l i c a
Linear search
Start at the beginning of the list and check
removal will be determined by the purpose
u
for the tree and how the tree is to be b every element of the list. Very slow [order
O(n) ] but works on an unsorted list.
ul P
maintained and/or processed. For example,
you might need a remove() method with a
2. Binary Search
This is used for searching in a sorted array.
a h
parameter that indicates which node of the
tree is to be removed (based on position, key
Test the middle element of the array. If it is
too big. Repeat the process in the left half of
R
data, or reference). To begin with, we will
assume no particular purpose or order and
therefore remove the root in such a way that
the tree will remain nearly balanced.
the array, and the right half if it’s too small.
In this way, the amount of space that needs
to be searched is halved every time, so the
time is O(log n).
Other operations that may be included as 3. Hash Search
needed: Searching a hash table is easy and extremely
height(): Determines the height of the tree. fast, just find the hash value for the item you’re
An empty tree will have height 0. looking for then go to that index and start
searching the array until you find what you
size(): Determines the number of nodes in
are looking for or you hit a blank spot. The
the tree.
order is pretty close to o(1), depending on
getRootData(): Returns the data (primative how full your hash table is.
data) or reference to the data (objects) of the
4. Binary Tree search
tree’s root.
getLeftSubtree(): Returns a reference to Search a binary tree is just as easy as searching
the left subtree of this tree. a hash table, but it is usually slower (especially
if the tree is badly unbalanced). Just start at
getRightSubtree(): Returns a reference to
the right subtree of this tree. the root. Then go down the left subtree if the
266
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
root is too big and the right subtree if is too often you encounter almost sorted elements. The
small. Repeat until you find what you want run time of insertions sort is O(n2) at worst case
or the sub-tree you want isn’t there. The scenario. So far we have another useless alternative
running time is O(log n) on average and O(n) for selection sort. But if implemented well the run
in the worst case. time can be reduced to O(n+k). n is the number of
elements and k is the number of inversions (the
5. Compare various sorting techniques
number of pair of elements out of order). With this
with real world usage.
new run time in mind you can see if the sequence is
Ans : almost sorted (k is small) the run time can be almost
Selection sort is an exception in our list. This linear which is a huge improvement over the
is considered an academic sorting algorithm. polynomial n2.
Because the time efficiency is always O(n2) which is Pros
not acceptable. There is no real world usage for
selection sort except passing the data structure course Easy to implement
exam. The more the sequence is ordered the closer
Pros is run time to linear time O(n)
Nothing Cons
cons
n s
Not suitable for large data sets
tio
Always run at O(n2) even at best case scenario Still polynomial at worst case
Bubble sort
This is the other exception in the list because
6.
l i c a
Apply the bubble sort algorithm to sort
the list of data: 2, 10, 6, 4, 8.
bubble sort is too slow to be practical. Unless the
u
sequence is almost sorted feasibility of bubble sort b
Ans :
ul P
is zero and the running time is O(n2). This is one of
the three simple sorting algorithms alongside
selection sort and insertion sort but like selection
Bubble Sort
The given list of data is 2, 10, 6, 4, 8
267
Rahul Publications
B.Sc. II YEAR III SEMESTER
Since 10 > 6, exchange position of 10 with Since, 6 > 4 exchange position of 4 with
position of element 6. position of 6
2 4 6 8 10
2 6 10 4 8 Step 3
Step 3 Compare the element with 8
Compare element 10 with element 4 4
2 6 8 10
2 6 10 4 8
Since, 6 < 8 exchanging of an element’s
position is not required.
Since, 10 > 4, exchange position of 10 with
position of 4. 2 4 6 8 10
This is end of iteration 2, 8 is patched before
2 6 4 10 8 with the element 10.
Step 4 Iteration 3
n s
tio
Compare element 2 with element 4
2 6 4 10 8
l
2
i c a 4 6 8 10
2 6 4
ul
8 P 10
Step 2
Compare element 4 with 6
a h
As the end of array is reached the iteration 1
terminates. the last element 10 does not 2 4 6 8 10
Iteration 2
R
require further processing.
Since, 4 < 6 exchanging of an element’s
position is not required.
Step 1
Compare element 2 with 6 2 4 6 8 10
This is end of the iteration 3, the element 6 is
2 6 4 8 10 patched before the element 8.
Iteration 4
Since, 2< 6 exchanging of an element’s Compare element 2 with 4
position is not required.
2 4 6 8 10
Step 2
Compare element 6 with 4
Since, 2 < 4 exchanging of an element’s
position is not required.
2 6 4 8 10
2 4 6 8 10
268
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
This is end of the iteration 4, the element 4 is patched before the element 6.
Since, the only element left is 2, it is patched before 4.
Finally, the completely sorted list of elements obtained is given below,
2 4 6 8 10
Ans :
Given that,
Inorder D B H E A I F J C G
Preorder A B D E H C F I J G
In preorder traversal of a binary tree, the root node is traversed first. So, the first value in the
traversed.
n s
preorder traversal gives the root of the binary tree. Then the left subtree followed by the right subtree are
tio
In the inorder traversal, the left subtree is traversed initially and then the root is visited. Finally, the
right subtree is traversed.
i c a
A binary tree can be constructed from the given preorder and inorder traversals. Consider the
l
above given data, where the first element in preorder is ‘A’, so the element ‘A’ is the root node. The
u b
elements before ‘A’ in the inorder list i.e., (DBHE) becomes the left subtree and the elements after ‘A’ in
the inorder list i.e., (1FJCG) becomes the right subtree. This can be shown in figure (a).
ul P A
a h
R
In:DBHE In: IFJCG
Pre: BDEH Pre: CFIJG
Figure (a)
In the left subtree, the first element in preorder list is ‘B’. So, ‘B’ becomes the root node. The
elements on the left side of ‘B’ in the inorder list i.e., (D) becomes the left subtree and the elements on the
right side of B in the inorder list i.e., (HE) becomes the right subtree. This can be shown in figure (b).
B In : IFJCG
Pre: CFIJG
In: D In: HE
Pre: D Pre: EH
Figure (b)
269
Rahul Publications
B.Sc. II YEAR III SEMESTER
Now, consider the left subtree of node B, the only element in preorder is ‘D’ So, ‘D’ becomes the
leaf node. But, in the inorder list, there is only element i.e., ‘D’. So both left subtree and right subtree
cannot be formed. This can be shown in figure (c).
B In : IFJCG
Pre: CFIJG
D In: HE
Pre: EH
Figure (c)
Now, consider the right subtree of node ‘B’, the first element in preorder list is E. So, ‘E’ becomes
the root mode of the right subtree. In the inorder list, the elements on the leftside of ‘E’ i.e., (H) becomes
the left subtree of ‘E’ and since there are no elements on the rightsides of’E’, there is no right subtree for
‘E’. This can be shown in figure (d).
A
n s
tio
B In : IFJCG
Pre : CFIJG
D E
l i c a
u H
b
ul P
Hence, the left subtree of node ‘A’ is completed.
Figure (d)
a h
Now, consider the right subtree of root node ‘A’. In the right subtree, the first element in preorder
R
is ‘C’, So ‘C’ becomes the root node. In the inorder list, the elements on leftside of‘C’ i.e., (IFJ)
becomes left subtree and the element on rightside of‘C’ i.e., ‘G’ becomes right subtree. This can be
shown in figure (e).
B C
In : IFJ In : G
D E
Pre : FIJ Pre : G
Figure (e)
Now, consider the left subtree of node ‘C’. The first element in the preorder i.e., ‘F’ becomes root
node. In the inorder list, the elements on the leftside of “F’ i.e., (I) becomes left subtree and the elements
on the rightside of ‘F’ i.e., (J) becomes right subtree. This can be shown in figure (f).
270
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
C
B
D E F In : G
Pre : G
H I J
Figure (f)
Now, consider the right subtree of node ‘C’, the only element in preorder is ‘G’ so it becomes leaf
node. In the inorder list, there is only one element i.e., ‘G’. So both left subtree and right subtree cannot
be formed. This can be shown in figure (g).
B
C
n s
D E F
c a
G
tio
H I
b l i J
P u Figure (g)
ul
Hence, the right subtree of node ’A’ is completed and figure (g) gives the final binary tree constructed
h
for the given preorder and inorder lists.
8.
a
Define internal and external sorting.
Ans : R
Internal Sorting : If the Input data is such that it can be adjusted in the main memory.
External Sorting : If the input data is such that it cannot be adjusted in the memory entirely at
once, It needs to be stored is external memory.
9. What are the pros of binary search.
Ans :
The binary search algorithm is more efficient than the linear search algorithm because it takes less
time to search through the list. It has a logarithmic relationship between the number of elements (N) in the
list, and the number of comparisons required (C), given by the following formula.
10. What are the applications of trees?
Ans :
Some of the applications of trees are,
1. Manipulation of arithmetic expression
2. Constructing symbol table
3. Maintaining symbol table
271
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio [c]
(a) Left SubTree, Right SubTree, Root
(c) Root, Left SubTree Right SubTree
u b li
(b) Right SubTree, Left SubTree, Root
(d) Right SubTree, Root, Left SubTree
6.
l
Linked Representation of binary tree need
ah
(a) 4 (b) 2
(c) 3 (d) 5
7.
R
Graphs are represented using
(a) Adjacency Tree (b) Adjacency Linked List/ Matrix
[b]
272
Rahul Publications
UNIT - III DATA STRUCTURE USING C++
7. Graph is nonlinear data structure which contains set of points known as and .
8. A Graph with un directed edges is called .
9. A graph is said to be graph if all its vertices have the same degree.
n s
tio
11. We use Data structure to implement minimum spanning tree.
l i c a
u
ANSWERS
b
1.
2.
Tree
N-1
ul P
3. Edge
a h
4.
5.
Binary
R
Proper Binary Tree or 2 - Tree
6. Binary Tree Traversal
7. Nodes, Links
8. Undirected Graphs
9. Regular
10. Spanning
11. Queue
12. Hasing
273
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
A binary tree ‘T’ is defined by finite set of elements called nodes such that,
(a) A binary tree is empty or
c a tio
subtree of the root.
b l i
(b) It consists of a node called ‘root’ which includes two binary trees called left subtree and right
4. Define searching.
P u
ul
Ans :
a h
Searching is a process done to know the correct location of an element from a list or array of
elements. In an array, elements are stored in consecutive memory locations. Searching is done by comparing
R
a particular element with the remaining elements until the exact match is found.
274
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Vertex
4.1 GRAPHS
4.1.1 Introduction A individual data element of a graph is called
as Vertex. Vertex is also known as node. In above
Q1. What is graph? Discuss the terminology
example graph, A, B, C, D & E are known as
of graph.
vertices.
Ans :
Edge
n s
tio
Graph is a non linear data structure, it contains
a set of points known as nodes (or vertices) and set An edge is a connecting link between two
of links known as edges (or Arcs) which connects
the vertices. A graph is defined as follows:
l i a
vertices. Edge is also known as Arc. An edge is
c
represented as (startingVertex, endingVertex). For
Graph is a collection of vertices and arcs which
u b
example, in above graph, the link between vertices
connects vertices in the graph
ul P
Graph is a collection of nodes and edges
A and B is represented as (A,B). In above example
graph, there are 7 edges (i.e., (A, B), (A, C), (A,D),
(B, D), (B, E), (C,D), (D, E)).
a h
which connects nodes in the graph
Generally, a graph G is represented as G Edges are three types.
of edges. R
= ( V , E ), where V is set of vertices and E is set
1. Undirected Edge: An undirected egde is a
bidirectional edge. If there is a undirected
Example
edge between vertices A and B then edge
The following is a graph with 5 vertices and 6 (A, B) is equal to edge (B, A).
edges. This graph G can be defined as G = (V , E )
2. Directed Edge: A directed egde is a
Where,
unidirectional edge. If there is a directed edge
V = {A,B,C,D,E} and
between vertices A and B then edge (A , B)
E = {(A,B),(A,C)(A,D),(B,D), (C,D),(B,E), is not equal to edge (B, A).
(E,D)}.
3. Weighted Edge: A weighted egde is an edge
with cost on it.
Undirected Graph
We use the following terms in graph data A graph with only undirected edges is said to
structure. be undirected graph.
275
Rahul Publications
B.Sc. II YEAR III SEMESTER
A graph with only directed edges is said to be Total number of outgoing edges connected
directed graph. to a vertex is said to be outdegree of that vertex.
tio
to be origin of it and the other endpoint is said to parallel and self-loop edges.
be the destination of the edge.
Adjacent
Path
l i c a
A path is a sequence of alternating vertices
If there is an edge between vertices A and B
u b
and edges that starts at a vertex and ends at a vertex
ul P
then both A and B are said to be adjacent. In other
words, Two vertices A and B are said to be adjacent
if there is an edge whose end vertices are A and B.
such that each edge is incident to its predecessor
and successor vertex.
Incident
R ah
An edge is said to be incident on a vertex if
the vertex is one of the endpoints of that edge.
4.1.2 Representation of Graphs
276
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
vertices. That means if a graph with 4 vertices can be represented using a matrix of 4X4 class. In this
matrix, rows and columns both represents vertices. This matrix is filled with either 1 or 0. Here, 1
represents there is an edge from row vertex to column vertex and 0 represents there is no edge
from row vertex to column vertex.
For example, consider the following undirected graph representation...
n s
c a tio
b l i
P u
2.
a h
Incidence Matrix ul
R
In this representation, graph can be represented using a matrix of size total number of vertices by
total number of edges. That means if a graph with 4 vertices and 6 edges can be represented using
a matrix of 4X6 class. In this matrix, rows represents vertices and columns represents edges. This
matrix is filled with either 0 or 1 or -1. Here, 0 represents row edge is not connected to column
vertex, 1 represents row edge is connected as outgoing edge to column vertex and -1 represents
row edge is connected as incoming edge to column vertex.
For example, consider the following directed graph representation...
277
Rahul Publications
B.Sc. II YEAR III SEMESTER
3. Adjacency List
In this representation, every vertex of graph contains list of its adjacent vertices.
For example, consider the following directed graph representation implemented using linked list...
n s
4.2 GRAPH TRAVERSAL
c a tio
4.2.1 Depth First Search
Q3. Explain DFS algorithm with an example.
b l i
Ans :
P u (June-18)
a h ul
DFS traversal of a graph, produces a spanning tree as final result. Spanning Tree is a graph
R
without any loops. We use Stack data structure with maximum size of total number of vertices in the
graph to implement DFS traversal of a graph.
We use the following steps to implement DFS traversal...
Step 1: Define a Stack of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it on to the
Stack.
Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack which is not
visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top of the stack.
Step 5: When there is no new vertex to be visit then use back tracking and pop one vertex from
the stack.
Step 6: Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7: When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph Back tracking is coming back to the vertex from which we came to current vertex.
278
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Example
Consider the following example graph to perform UPS traversal
Step 1:
• Select the vertex A as starting point (visit A).
• Push A on to the Stack
n s
c a tio
Step 2:
•
b l i
Visit any adjacement vertex of A which is not visited(B).
•
u
Push newly visited vertex B on to the Stack
P
a h ul
R
Step 3:
• Visit any adjacement vertex of B which is not visited(C)
• Push C on to the Stack
279
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step 4:
• Visit any adjacement vertex of C which is not visited(E)
• Push E on to the Stack
Step 5:
• Visit any adjacement vertex of E which is not visited(D)
• Push D on to the Stack
n s
c a tio
b l i
Step 6:
•
P u
There is no new vertiex to be visited from D. So use back track
ul
• Pop D from the Stack
a h
R
Step 7:
• Visit any adjacement vertex of E which is not visited(F)
• Push F on to the Stack
280
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Step 8:
• Visit any adjacement vertex of F which is not visited(G)
• Push G on to the Stack
Step 9:
• There is no new vertiex to be visited from G. So use back track
• Pop G from the Stack
n s
c a tio
Step 10:
b l i
•
u
There is no new vertiex to be visited from F. So use back track
P
ul
• Pop F from the Stack
a h
R
Step 11:
• There is no new vertiex to be visited from E. So use back track
• Pop F from the Stack
281
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step 12:
• There is no new vertiex to be visited from C. So use back track
• Pop C from the Stack
Step 13:
• There is no new vertiex to be visited from B. So use back track
• Pop B from the Stack
n s
c a tio
b l i
Step 14:
•
P u
There is no new vertiex to be visited from A. So use back track
• Pop A from the Stack
a h ul
R
Step 15:
• Stack became Empty. So stop DFS Treversa
• Final result of DFS traversa is following spanning tre
282
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
l i c a
for(k=1;k<=m;k++)
u b
14
47
{
cin >>i>>j;
ul P 57
78
ah
cost[i][j]=1;
} 89
R
cout <<“enter initial vertex”;
cin >>v;
enter initial vertex1
ORDER OF VISITED VERTICES1 2 3 6 4 7 8 9 5
cout <<“ORDER OF VISITED VERTICES”; 4.2.2 Breadth First Search
cout << v <<“ “; Q5. Explain about BFS algorithm with an
example.
visited[v]=1;
k=1; Ans : (June-18)
while(k<n) BFS (Breadth First Search)
{ BFS traversal of a graph, produces a spanning
tree as final result. Spanning Tree is a graph
for(j=n;j>=1;j—)
without any loops. We use Queue data
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1) structure with maximum size of total number of
{ vertices in the graph to implement BFS traversal of
a graph.
visit[j]=1;
We use the following steps to implement BFS
stk[top]=j; traversal.
283
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Step 1:
c a tio
•
•
Select the vertex A as starting point (visit A)
Insert A into the Queue
b l i
P u
a h ul
Step 2:
•
•
R
Visit all adjacent vertices of A which are not visited (D, E, B)
Insert newly visited vertices into the Queue and delete A from the Queue
Step 3:
• Visit all adjacent vertices of D which are not visited (there is no vertex)
• Delete D from the Queue
284
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Step 4:
• Visit all adjacent vertices of E which are not visited (C, F)
• Insert newly visited vertices into the Queue and delete E from the Queue
Step 5:
• Visit all adjacent vertices of B which are not visited (there is no vertex)
• Delete B from the Queue
n s
c a tio
b l i
Step 6:
P u
ul
• Visit all adjacent vertices of C which are not visited (G)
• Insert newly visited vertices into the Queue and delete C from the Queue
a h
R
Step 7:
• Visit all adjacent vertices of F which are not visited (there is no vertex)
• Delete F form the Queue
285
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step 8:
• Visit all adjacent vertices of G which are not visited (there is no vertex)
• Delete G form the Queue
Step 9:
• Queue became Empty. So, stop the BFS process
• Final result of BFS is a Spaning Tree as shown below
c a tio
#include <iostream>
#include <conio.h>
b l i
usingnamespace std;
P u
ul
int c =0, t =0;
struct node_info
{
a h
int no;
int st_time;
R
}*q =NULL, *r =NULL, *x =NULL;
struct node
{
node_info *pt;
node *next;
}*front =NULL, *rear =NULL, *p =NULL, *np =NULL;
void push(node_info *ptr)
{
np =new node;
np->pt = ptr;
np->next =NULL;
286
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
if(front ==NULL) {
{ if(am[i][j]==0||(am[i][j]==1&& v[j]==1))
front = rear = np; continue;
rear->next =NULL; elseif(am[i][j]==1&& v[j]==0)
} {
else r =new node_info;
{ r->no = j;
rear->next = np; r->st_time = t++;
rear = np; cout<<“time of visitation for node “<<r-
rear->next =NULL; >no<<“:”<<r->st_time<<“\n\n”;
} v[j]=1;
} push(r);
node_info *remove() }
{ }
if(front ==NULL) remove();
{ if(c <=6&& front !=NULL)
n s
tio
cout<<“empty queue\n”;
bfs(v, am, remove()->no);
}
else
{
}
l i c a
int main()
b
{
Pu
p = front;
int v[7], am[7][7];
x = p->pt;
l
front = front->next;
u
for(int i =0; i <7; i++)
v[i]=0;
ah
delete(p);
for(int i =0; i <7; i++)
return(x);
}
} R
void bfs(int*v,int am[][7],int i)
{
cout<<“enter the values for adjacency matrix
row:”<<i+1<<endl;
for(int j =0; j <7; j++)
{
{
if(c ==0)
cin>>am[i][j];
{
}
q =new node_info;
q->no = i; }
q->st_time = t++; bfs(v, am, 0);
cout<<“time of visitation for node getch();
“<<q->no<<“:”<<q->st_time<<“\n\n”; 1. }
v[i]=1; Output
push(q); enter the values for adjacency matrix row:1
} 0
c++; 1
for(int j =0; j <7; j++) 1
287
Rahul Publications
B.Sc. II YEAR III SEMESTER
0
0
1
1
enter the values for adjacency matrix row:2
1
0
0
0
0
0
0
enter the values for adjacency matrix row:3
1
n s
0
0
c a tio
0
b l i
0
0
P u
1
a h ul
time of visitation for node 0:0
R
time of visitation for node 1:1
time of visitation for node 2:2
Ans : (Nov.-17)
If we have a graph containing V vertices and E edges, then the graph can be represented as:
G(V, E)
If we create the spanning tree from the above graph, then the spanning tree would have the
same number of vertices as the graph, but the vertices are not equal. The edges in the spanning tree
would be equal to the number of edges in the graph minus 1.
Suppose the spanning tree is represented as:
G‘(V‘, E‘)
where,
288
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
V=V‘
E‘ E -1
E‘=|V| - 1
Let’s understand through an example.
Suppose we want to create the spanning tree of the graph, which is shown below:
n s
tio
As we know, that spanning tree contains the same number of vertices as the graph, so the total number of
vertices in the graph is 5; therefore, the spanning tree will also contain the 5 vertices. The edges in the
l i c a
spanning tree are equal to the number of vertices in the graph minus 1; therefore, the number of edges
is 4. Three spanning trees can be created, which are shown below:
u b
ul P
a h
R
Ans : (June-18)
Minimum Spanning Trees
The minimum spanning tree is the tree whose sum of the edge weights is minimum. From the
above spanning trees, the total edge weight of the spanning tree 1 is 12, the total edge weight of the
spanning tree 2 is 14, and the total edge weight of the spanning tree 3 is 11; therefore, the total edge
weight of the spanning tree 3 is minimum. From the above graph, we can also create one more spanning
tree as shown below:
289
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
The spanning tree cannot be disconnected.
tio
If we remove one more edge from any of
A connected graph can contain more than
the above spanning trees as shown below:
one spanning tree. The spanning trees which
are minimally connected or we can say that
the tree which is having a minimum total edge
l i c a
The above tree is not a spanning tree because
it is disconnected now.
weight would be considered as the minimum
spanning tree.
u b
If two or three edges have the same edge
weight, then there would be more than two
ul P
All the possible spanning trees that can be
created from the given graph G would have
minimum spanning trees. If each edge has a
distinct weight, then there will be only one or
ah
the same number of vertices, but the number unique minimum spanning tree.
of edges in the spanning tree would be equal A complete undirected graph can have
minus 1. R
to the number of vertices in the given graph
290
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
We can create three spanning trees from the above graph shown as below:
n s
c a tio
b l i
P u
a h ul
R
According to this property, the maximum number of edges from the graph can be formulated as
(e-n+1) where e is the number of edges, n is the number of vertices. When we substitute the value
of e and n in the formula, then we get 1 value. It means that we can remove maximum 1 edge from
the graph to make a spanning tree. In the above spanning trees, the one edge has been removed.
Applications of Spanning trees
The following are the applications of the spanning trees:
Building a network: Suppose there are many routers in the network connected to each other, so
there might be a possibility that it forms a loop. So, to avoid the formation of the loop, we use the
tree data structure to connect the routers, and a minimum spanning tree is used to minimally
connect them.
Clustering: Here, clustering means that grouping the set of objects in such a way that similar objects
belong to the same group than to the different group. Our goal is to divide the n objects into k
groups such that the distance between the different groups gets maximized.
291
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Prim’s Algorithm is used to find the minimum spanning tree from a graph. Prim’s algorithm finds
the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges
can be minimized.
Prim’s algorithm starts with the single node and explore all the adjacent nodes with all the connecting
edges at every step. The edges with the minimal weights causing no cycles in the graph got selected.
The algorithm is given as follows.
Algorithm
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe vertices
Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum weight
n s
Step 4: Add the selected edge and the vertex to the minimum spanning tree T
tio
[END OF LOOP]
Step 5: EXIT
i c a
Q10. Construct a minimum spanning tree of the graph given in the following figure by using
prim’s algorithm.
l
u b
ul P
a h
R
Sol :
Step 1 : Choose a starting vertex B.
Step 2: Add the vertices that are adjacent to A. the edges that connecting the vertices are shown
by dotted lines.
Step 3: Choose the edge with the minimum weight among all. i.e. BD and add it to MST. Add the
adjacent vertices of D i.e. C and E.
Step 3: Choose the edge with the minimum weight among all. In this case, the edges DE and CD
are such edges. Add them to MST and explore the adjacent of C i.e. E and A.
Step 4: Choose the edge with the minimum weight i.e. CA. We can’t choose CE as it would cause
cycle in the graph.
292
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
The graph produces in the step 4 is the minimum spanning tree of the graph shown in the above
figure.
The cost of MST will be calculated as;
cost(MST) = 4 + 2 + 1 + 3 = 10 units.
n s
c a tio
b l i
P u
a h ul
Q11. Write a program to implement Prim’s Algorithm.
Ans :
R
#include<iostream>
(Nov.-17)
usingnamespace std;
// Number of vertices in the graph
constint V=6;
// Function to find the vertex with minimum key value
intmin_Key(int key[],bool visited[])
{
int min =999, min_index;// 999 represents an Infinite value
for(int v =0; v < V; v++){
if(visited[v]==false&& key[v]< min){
// vertex should not be visited
min = key[v];
293
Rahul Publications
B.Sc. II YEAR III SEMESTER
min_index = v;
}
}
return min_index;
}
// Function to print the final MST stored in parent[]
intprint_MST(int parent[],int cost[V][V])
{
int minCost=0;
cout<<“Edge \tWeight\n”;
for(int i =1; i< V; i++){
cout<<parent[i]<<“ - “<<i<<“ \t”<<cost[i][parent[i]]<<“ \n”;
minCost+=cost[i][parent[i]];
}
cout<<“Total cost is”<<minCost;
}
n s
tio
// Function to find the MST using adjacency cost matrix representation
voidfind_MST(int cost[V][V])
{
l i c a
int parent[V], key[V];
bool visited[V];
u b
// Initialize all the arrays
for(int i =0; i< V; i++){
ul P
a
visited[i]=false;h
key[i]=999;// 99 represents an Infinite value
}
parent[i]=-1;
R
key[0]=0;// Include first vertex in MST by setting its key vaue to 0.
parent[0]=-1;// First node is always root of MST
// The MST will have maximum V-1 vertices
for(int x =0; x < V -1; x++)
{
// Finding the minimum key vertex from the set of vertices not yet included in MST
int u =min_Key(key, visited);
visited[u]=true;// Add the minimum key vertex to the MST
// Update key and parent arrays
for(int v =0; v < V; v++)
{
// cost[u][v] is non zero only for adjacent vertices of u
// visited[v] is false for vertices not yet included in MST
294
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
tio
for(int j=0;j<V;j++)
{
}}
cin>>cost[i][j];
l i c a
find_MST(cost);
u b
return0;
}
ul P
a h
The input graph is the same as the graph in Fig 2.
Enter the vertices for a graph with 6 vetices
R
0 4 0 0 0 2
4 0 6 0 0 3
0 6 0 3 0 1
0 0 3 0 2 0
0 0 0 2 0 4
2 3 1 0 4 0
Edge Weight
5-1 3
5-2 1
2-3 3
3-4 2
0-5 2
Total cost is 11
295
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans : (Imp.)
Kruskal’s Algorithm is used to find the minimum spanning tree for a connected weighted graph.
The main target of the algorithm is to find the subset of edges by using which, we can traverse every
vertex of the graph. Kruskal’s algorithm follows greedy approach which finds an optimum solution at
every stage instead of focusing on a global optimum.
The Kruskal’s algorithm is given as follows.
Algorithm
Step 1: Create a forest in such a way that each graph is a separate tree.
Step 2: Create a priority queue Q that contains all the edges of the graph.
Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY
Step 4: Remove an edge from Q
combining two trees into one tree).
n s
Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it to the forest (for
ELSE
Discard the edge
c a tio
Step 6: END
b l i
Example :
P u
ul
Apply the Kruskal’s algorithm on the graph given as follows.
a h
R
Sol:
the weight of the edges given as :
Edge AE AD AC AB BC CD DE
Weight 5 10 7 1 3 4 2
296
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Edge AB DE BC CD AE AC AD
Weight 1 2 3 4 5 7 10
n s
c a tio
b l i
P u
Add BC to the MST;
a h ul
R
297
Rahul Publications
B.Sc. II YEAR III SEMESTER
The next step is to add AE, but we can’t add void print();
that as it will cause a cycle.
};
The next edge to be added is AC, but it can’t
Graph::Graph(int V) {
be added as it will cause a cycle.
parent = new int[V];
The next edge to be added is AD, but it can’t
be added as it will contain a cycle. //i 0 1 2 3 4 5
Hence, the final MST is the one which is //parent[i] 0 1 2 3 4 5
shown in the step 4.
for (int i = 0; i < V; i++)
the cost of MST = 1 + 2 + 3 + 4 = 10.
parent[i] = i;
The steps for implementing Kruskal’s
G.clear();
algorithm are as follows:
T.clear();
1. Sort all the edges from low weight to high
2. Take the edge with the lowest weight and add }
it to the spanning tree. If adding the edge void Graph::AddWeightedEdge(int u, int v, int w) {
created a cycle, then reject this edge.
3. Keep adding edges until we reach all vertices.
} s
G.push_back(make_pair(w, edge(u, v)));
n
tio
Q13. Write a program to implement kruskal’s
algorithm int Graph::find_set(int i) {
Ans :
l i c a
// If i is the parent of itself
u b if (i == parent[i])
return i;
#include <algorithm>
#include <iostream>
ul P else
// Else if i is not the parent of itself
ah
#include <vector>
// Then i is not the representative of his set,
R
using namespace std;
// so we recursively call Find on its parent
#define edge pair<int, int>
return find_set(parent[i]);
class Graph {
private: }
int *parent; }
298
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
tio
int main() {
Graph g(6);
g.AddWeightedEdge(0, 1, 4);
l i c a
g.AddWeightedEdge(0, 2, 4);
u b
g.AddWeightedEdge(1, 2, 2);
g.AddWeightedEdge(1, 0, 4);
ul P
h
g.AddWeightedEdge(2, 0, 4);
a
R
g.AddWeightedEdge(2, 1, 2);
g.AddWeightedEdge(2, 3, 3);
g.AddWeightedEdge(2, 5, 2);
g.AddWeightedEdge(2, 4, 4);
g.AddWeightedEdge(3, 2, 3);
g.AddWeightedEdge(3, 4, 3);
g.AddWeightedEdge(4, 2, 4);
g.AddWeightedEdge(4, 3, 3);
g.AddWeightedEdge(5, 2, 2);
g.AddWeightedEdge(5, 4, 3);
g.kruskal();
g.print();
return 0;
}
299
Rahul Publications
B.Sc. II YEAR III SEMESTER
4.4 HASHING
4.4.1 Introduction
Q14. What is Hashing? Define it with an example.
Ans : (July-21)
Hashing is the process of mapping large amount of data item to smaller table with the help of
hashing function.
Hashing is also known as Hashing Algorithm or Message Digest Function.
It is a technique to convert a range of key values into a range of indexes of an array.
It is used to facilitate the next level searching method when compared with the linear or binary
search.
Hashing allows to update and retrieve any data entry in a constant time O(1).
Constant time O(1) means the operation does not depend on the size of the data.
Hashing is used with a database to enable items to be retrieved more quickly.
It is used in the encryption and decryption of digital signatures.
Example
n s
tio
Consider an example of hash table of size 20, and the following items are to be stored. Item are in
the (key,value) format.
l i c a
u b
ul P
a h
R
(1,20) , (2,70) , (42,80) , (4,25) , (12,44) , (14,32) , (17,11) , (13,78) , (37,98)
300
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
4.4.2 Key Terms and Issues Full table A full table is one in which all
Q15. Mention the key terms and issues of hash locations are occupied. Owing to the
table. characteristics of hash functions, there are
Ans : always empty locations, rather a hash
function should not allow the table to get filled
Hash table Hash table is an array [0 to Max in more than 75%.
– 1] of size Max.
Load factor Load factor is the number of
Bucket A bucket is an index position in a hash
records stored in a table divided by the
table that can store more than one record.
When the same index is mapped with two maximum capacity of the table, expressed in
keys, both the records are stored in the same terms of percentage.
bucket. The assumption is that the buckets Rehashing Rehashing is with respect to closed
are equal in size. hashing. When we try to store the record with
Probe Each action of address calculation and Key1 at the bucket position Hash(Key1) and
check for success is called as a probe. find that it already holds a record, it is collision
Collision The result of two keys hashing into situation. To handle collision, we use a strategy
the same address is called collision. to choose a sequence of alternative locations
Synonym Keys that hash to the same address
n s
Hash1(Key1), Hash2(Key1), and so on
within the bucket table so as to place the
tio
are called synonyms.
record with Key1. This is known as rehashing.
Overflow The result of many keys hashing to
a single address and lack of room in the bucket
is known as an overflow. Collision and
l i c a
Issues in hashing In case of collision, there
are two main issues to be considered:
overflow are synonymous when the bucket
b
1. We need a good hashing function that
Pu
is of size 1. minimizes the number of collisions.
Open or external hashing When we allow 2. We want an efficient collision resolution
l
records to be stored in potentially unlimited
u
space, it is called as open or external hashing.
strategy so as to store or locate synonyms.
ah
4.4.3 Hash Functions
Closed or internal hashing When we use fixed
Q16. What is Hash Function?
R
space for storage eventually limiting the
number of records to be stored, it is called as
closed or internal hashing.
Ans :
(June-18)
A fixed process converts a key to a hash key
Hash function Hash function is an arithmetic is known as a Hash Function.
function that transforms a key into an
This function takes a key and maps it to a
address which is used for storing and retrieving
value of a certain length which is called
a record. a Hash value or Hash.
Perfect hash function The hash function that
Hash value represents the original string of
transforms different keys into different
characters, but it is normally smaller than the
addresses is called a perfect hash function. original.
The worth of a hash function depends on
how It transfers the digital signature and then both
hash value and signature are sent to the
well it avoids collision. receiver. Receiver uses the same hash
Load density The maximum storage capacity, function to generate the hash value and then
that is, the maximum number of records compares it to that received with the message.
that can be accommodated, is called as loading If the hash values are same, the message is
density. transmitted without errors.
301
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
Hash function Hash function is one that maps a key in the range [0 to Max – 1], the result of which
is used as an index (or address) in the hash table for storing and retrieving records. One more way to
define a hash function is as the function that transforms a key into an address. The address generated by
a hashing function is called the home address. All home addresses refer to a particular area of the memory
called the prime area.
Division Hash Method
The key K is divided by some number m and the remainder is used as the hash address of K.
• h(k)=k mod m
This gives the indexes in the range 0 to m-1 so the hash table should be of size m
This is an example of uniform hash function if value of m will be chosen carefully.
Generally a prime number is a best choice which will spread keys evenly.
tio
For example: Let us say apply division approach to find hash value for some values
considering number of buckets be 10 as shown below.
l i c a
u b
ul P
a h
R
302
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
tio
The parts are then added together , ignoring the final carry, to form an address.
P1=356, P2=942, P3=781 are added to yield 079.
l i c a
Example: If key=356942781 is to be transformed into a three digit address.
u b
ul P
The key K is multiplied by itself and the address is obtained by selecting an appropriate number of
digits from the middle of the square.
a h
The number of digits selected depends on the size of the table.
Example: If key=123456 is to be transformed.
R
(123456)2=15241383936
If a three-digit address is required, positions 5 to 7 could be chosen giving address 138.
Universal hashing
If a malicious adversary chooses keys to be hashed, then he can choose n keys that all hash to the
same slot, yielding an average retrieval time of Q(n). Any fixed hash function is vulnerable to this sort of
worst case behavior. The only effective way to improve the situation is to choose a hash function randomly
in a way that is independent of the keys that are actually going to be stored.
This approach is referred to as universal hashing. In other words, universal hashing is to select the
hash function at random and at run time from a carefully designed collection of hash functions.
Let H = {h1,h2, . . . ,hl} be a finite collection of hash functions that map a given
universe U of keys into a range {0,1, . . . ,m–1}.
Such a collection is said to be universal if for each pair of distinct keys x, y 2U, the number of hash
H l
functions h 2 H for which h(x) = h(y) is at most
m m
303
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
When the two different values have the same value, then the problem occurs between the two
values, known as a collision. In the above example, the value is stored at index 6. If the key value is 26,
then the index would be:
h(26) = 26%10 = 6
n s
Therefore, two values are stored at the same index, i.e., 6, and this leads to the collision problem.
To resolve these collisions, we have some techniques known as collision techniques.
The following are the collision techniques:
Open Hashing: It is also known as closed addressing.
c a tio
b l
Closed Hashing: It is also known as open addressing.i
u
Q19. Explain Open Hashing method with an example.
P
ul
Ans :
Open Hashing
a h
R
In Open Hashing, one of the methods used to resolve the collision is known as a chaining method.
304
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
tio
• The index of key value 6 is:
index = h(6) = (2(6)+3)%10 = 5
The value 6 would be stored at the index 5.
l i c a
•
u
The index of key value 11 is:
b
index = h(11) = (2(11)+3)%10 = 5
ul P
The value 11 would be stored at the index 5. Now, we have two values (6, 11) stored at the same
a h
index, i.e., 5. This leads to the collision problem, so we will use the chaining method to avoid the collision.
We will create one more list and add the value 11 to this list. After the creation of the new list, the newly
•
R
created list will be linked to the list having value 6.
The index of key value 13 is:
index = h(13) = (2(13)+3)%10 = 9
The value 13 would be stored at index 9. Now, we have two values (3, 13) stored at the same
index, i.e., 9. This leads to the collision problem, so we will use the chaining method to avoid the collision.
We will create one more list and add the value 13 to this list. After the creation of the new list, the newly
created list will be linked to the list having value 3.
• The index of key value 7 is:
index = h(7) = (2(7)+3)%10 = 7
The value 7 would be stored at index 7. Now, we have two values (2, 7) stored at the same index,
i.e., 7. This leads to the collision problem, so we will use the chaining method to avoid the collision. We will
create one more list and add the value 7 to this list. After the creation of the new list, the newly created list
will be linked to the list having value 2.
• The index of key value 12 is:
index = h(12) = (2(12)+3)%10 = 7
305
Rahul Publications
B.Sc. II YEAR III SEMESTER
According to the above calculation, the value Let’s understand the linear probing
12 must be stored at index 7, but the value 2 exists through an example.
at index 7. So, we will create a new list and add 12 Consider the above example for the linear
to the list. The newly created list will be linked to probing:
the list having a value 7.
A = 3, 2, 9, 6, 11, 13, 7, 12 where m = 10,
The calculated index value associated with and h(k) = 2k+3
each key value is shown in the below table: The key values 3, 2, 9, 6 are stored at the
key Location(u) indexes 9, 7, 1, 5 respectively. The calculated
index value of 11 is 5 which is already
3 ((2*3)+3)%10 = 9 occupied by another key value, i.e., 6. When
linear probing is applied, the nearest empty
2 ((2*2)+3)%10 = 7
cell to the index 5 is 6; therefore, the value
9 ((2*9)+3)%10 = 1 11 will be added at the index 6.
6 ((2*6)+3)%10 = 5 The next key value is 13. The index value
associated with this key value is 9 when hash
11 ((2*11)+3)%10 = 5 function is applied. The cell is already filled at
13 ((2*13)+3)%10 = 9
n s
index 9. When linear probing is applied, the
nearest empty cell to the index 9 is 0;
tio
7 ((2*7)+3)%10 = 7 therefore, the value 13 will be added at the
index 0.
12 ((2*12)+3)%10 = 7
Q20. What is Closed Hashing? Explain Linear
l i c a
The next key value is 7. The index value
associated with the key value is 7 when hash
Ans :
probing with example.
a
to resolve the collision:h
In Closed hashing, three techniques are used index 8.
The next key value is 12. The index value
1.
2.
R
Linear probing
Quadratic probing
associated with the key value is 7 when hash
function is applied. The cell is already filled at
index 7. When linear probing is applied, the
nearest empty cell to the index 7 is 2;
3. Double Hashing technique
therefore, the value 12 will be added at the
1. Linear Probing index 2.
Linear probing is one of the forms of open 2. Quadratic Probing
addressing. As we know that each cell in the In case of linear probing, searching is
hash table contains a key-value pair, so when performed linearly. In contrast, quadratic
the collision occurs by mapping a new key to probing is an open addressing technique that
the cell already occupied by another key, then uses quadratic polynomial for searching until
linear probing technique searches for the a empty slot is found.
closest free locations and adds a new key to It can also be defined as that it allows the
that empty cell. In this case, searching is insertion ki at first free location
performed sequentially, starting from the from (u+i2)%m where i=0 to m-1.
position where the collision occurs till the Let’s understand the quadratic probing
empty cell is not found. through an example.
306
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
tio
Since location 6 is empty, so the value 11 will Index = (7+22)%10 = 1
be added at the index 6. When i=3
The next element is 13. When the hash
function is applied on 13, then the index
l i c a
Index = (7+32)%10 = 6
b When i=4
Pu
value comes out to be 9, which we already
discussed in the chaining method. At index Index = (7+42)%10 = 3
ul
9, the cell is occupied by another value, i.e.,
3. So, we will apply the quadratic probing
Since the location 3 is empty, so the value 12
would be stored at the index 3.
ah
technique to calculate the free location.
The final hash table would be:
When i=0
R
Index = (9+02)%10 = 9
When i=1
Index = (9+12)%10 = 0
Since location 0 is empty, so the value 13 will
be added at the index 0.
The next element is 7. When the hash
function is applied on 7, then the index value
comes out to be 7, which we already
discussed in the chaining method. At index
7, the cell is occupied by another value, i.e.,
7. So, we will apply the quadratic probing
technique to calculate the free location.
When i=0
Index = (7+02)%10 = 7
When i=1
307
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s 1
tio
2 ((2*2)+3)%10 = 7 - 1
9
6
((2*9)+3)%10 = 1
((2*6)+3)%10 = 5
l
-
i
-
c a 1
1
11 ((2*11)+3)%10 = 5
b (3(11)+1)%10 =4 3
13
7
((2*13)+3)%10 = 9
ul
((2*7)+3)%10 = 7 Pu (3(13)+1)%10 = 0
(3(7)+1)%10 = 2
ah
12 ((2*12)+3)%10 = 7 (3(12)+1)%10 = 7 2
R
As we know that no collision would occur while inserting the keys (3, 2, 9, 6), so we will not apply
double hashing on these key values.
On inserting the key 11 in a hash table, collision will occur because the calculated index value of 11
is 5 which is already occupied by some another value. Therefore, we will apply the double hashing
technique on key 11. When the key value is 11, the value of v is 4.
Now, substituting the values of u and v in (u+v*i)%m
When i=0
Index = (5+4*0)%10 =5
When i=1
Index = (5+4*1)%10 = 9
When i=2
Index = (5+4*2)%10 = 3
Since the location 3 is empty in a hash table; therefore, the key 11 is added at the index 3.
308
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
The next element is 13. The calculated index The next element is 12. The calculated index
value of 13 is 9 which is already occupied by some value of 12 is 7 which is already occupied by some
another key value. So, we will use double hashing another key value. So, we will use double hashing
technique to find the free location. The value of v technique to find the free location. The value of v
is 0. is 7.
Now, substituting the values of u and v in Now, substituting the values of u and v in
(u+v*i)%m (u+v*i)%m
When i=0
When i=0
Index = (9+0*0)%10 = 9
Index = (7+7*0)%10 = 7
We will get 9 value in all the iterations from 0
to m-1 as the value of v is zero. Therefore, we cannot When i=1
insert 13 into a hash table.
Index = (7+7*1)%10 = 4
The next element is 7. The calculated index
value of 7 is 7 which is already occupied by some Since the location 4 is empty; therefore, the
another key value. So, we will use double hashing key 12 is inserted at the index 4.
technique to find the free location. The value of v
is 2.
n s
The final hash table would be:
tio
Now, substituting the values of u and v in
(u+v*i)%m
When i=0
Index = (7 + 2*0)%10 = 7
l i c a
When i=1
u b
Index = (7+2*1)%10 = 9
When i=2
ul P
When i=3
a h
Index = (7+2*2)%10 = 1
When i=4
R
Index = (7+2*3)%10 = 3
Index = (7+2*4)%10 = 5
When i=5
Index = (7+2*5)%10 = 7
When i=6
Index = (7+2*6)%10 = 9
When i=7
Index = (7+2*7)%10 = 1
When i=8
Index = (7+2*8)%10 = 3
When i=9
Index = (7+2*9)%10 = 5
Since we checked all the cases of i (from 0
The order of the elements is _, 9, _, 11, 12,
to 9), but we do not find suitable place to insert 7.
6, _, 2, _, 3.
Therefore, key 7 cannot be inserted in a hash table.
309
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
Q22. What is extendible hashing ? Explain
with a help of an example.
tio
Array linear list.
Ans :
Chain.
Open addressing is performed to ensure that
l i c a
It is an approach that tries to make hashing
all elements are stored directly into the hash table,
u
thus it attempts to resolve collisions implementing b dynamic,i.e. to allow insertions and deletions
to occur without resulting in poor
various methods.
ul P
Linear Probing is performed to resolve
performance after many of these operations.
Extendible hashing combines two ingredients:
in the table.
a h
collisions by placing the data into the next open slot
Hashing and tries.
tries are digital trees like the one used in
R
Performance of Linear Probing
Worst-case find/insert/erase time is è(m),
Lempel-¡ iv
Keys are placed into buckets,which are
independent parts of a file in disk.
where m is treated as the number of pairs in
the table. Keys having a hashing address with the same
prefix share the same bucket.
This occurs when all pairs are in the same
cluster. Atrie is used for fast access to the buckets. It
uses a prefix of the
Problem of Linear Probing
hashing address in order to locate the desired
Identifiers are tending to cluster together bucket.
Adjacent clusters are tending to coalesce Example
Increase or enhance the search time Assume that the hash function {\displaystyle
h(k)}h returns a string of bits. The first i bits of each
Quadratic Probing
string will be used as indices to figure out where
Linear probing searches buckets they will go in the “directory” (hash table).
(H(x)+i2)%b; H(x) indicates Hash function Additionally, i is the smallest number such that the
of x index of every item in the table is unique.
310
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
there is no other directory pointers that can map to
the bucket, so the directory must be doubled (case1).
a tio
If the bucket is full, if the local depth is less
than the global depth, then there exists more than
c
b l i
one pointer from the directory to the bucket, and
the bucket can be split (case 2).
P u
And so now k 1 and k 3 have a unique
ul
location, being distinguished by the first two leftmost
h
bits. Because k2 is in the top half of the table, both
a
00 and 01 point to it because there is no other key
R
to compare to that begins with a 0.
Now, k4 needs to be inserted, and it has the
first two bits as 01..(1110), and using a 2 bit depth
in the directory, this maps from 01 to Bucket A.
Bucket A is full (max size 1), so it must be split;
because there is more than one pointer to Bucket
A, there is no need to increase the directory size. Key 01 points to Bucket A, and Bucket A’s
What is needed is information about: local depth of 1 is less than the directory’s global
depth of 2, which means keys hashed to Bucket A
1. The key size that maps the directory (the have only used a 1 bit prefix (i.e. 0), and the bucket
global depth), and needs to have its contents split using keys 1 + 1 =
2. The key size that has previously mapped the 2 bits in length; in general, for any local depth d
bucket (the local depth) where d is less than D, the global depth, then d
must be incremented after a bucket split, and the
In order to distinguish the two action cases:
new d used as the number of bits of each entry’s
1. Doubling the directory when a bucket key to redistribute the entries of the former bucket
becomes full into the new buckets.
311
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
tio
So Bucket D needs to be split, but a check of
its local depth, which is 2, is the same as the global
depth, which is 2, so the directory must be split again,
in order to hold keys of sufficient detail, e.g. 3 bits.
l i c a
b
ul Pu Now, k2 is in D and E is tried again, with
3 bits 011.., and it points to bucket D which already
contains k2 so is full; D’s local depth is 2 but now
312
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Ans :
A complete binary tree is a binary tree in which all the levels except the last level, i.e., leaf node
should be completely filled, and all the nodes should be left-justified.
Let’s understand through an example.
n s
a
node; therefore, we can say that the above tree is a complete binary tree.
c tio
In the above figure, we can observe that all the internal nodes are completely filled except the leaf
b l i
P u
a h ul
R
The above figure shows that all the internal nodes are completely filled except the leaf node, but the
leaf nodes are added at the right part; therefore, the above tree is not a complete binary tree.
Q25. What are the different types of heaps? Explain Max heap algorithm with an example
Ans :
There are two types of the heap:
• Min Heap
• Max heap
Min Heap: The value of the parent node should be less than or equal to either of its children.
Or
In other words, the min-heap can be defined as, for every node i, the value of node i is greater than
or equal to its parent value except the root node. Mathematically, it can be defined as:
313
Rahul Publications
B.Sc. II YEAR III SEMESTER
In the above figure, 11 is the root node, and the value of the root node is less than the value of all
the other nodes (left child or a right child).
n s
tio
Max Heap: The value of the parent node is greater than or equal to its children.
Or
l i c a
In other words, the max heap can be defined as for every node i; the value of node i is less than or
equal to its parent value except the root node. Mathematically, it can be defined as:
A[Parent(i)] >= A[i]
u b
ul P
a h
R
The above tree is a max heap tree as it satisfies the property of the max heap. Now, let’s see the
array representation of the max heap.
Time complexity in Max Heap
The total number of comparisons required in the max heap is according to the height of the tree.
The height of the complete binary tree is always logn; therefore, the time complexity would also be
O(logn).
Algorithm of insert operation in the max heap.
/ algorithm to insert an element in the max heap.
314
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
insertHeap(A, n, value)
{
n=n+1; // n is incremented to insert the new element
A[n]=value; // assign new value at the nth position
i = n; // assign the value of n to i
// loop will be executed until i becomes 1.
while(i>1)
{
parent= floor value of i/2; // Calculating the floor value of i/2
// Condition to check whether the value of parent is less than the given node or not
if(A[parent]<A[i])
{
swap(A[parent], A[i]);
i = parent;
n s
tio
}
a
else
{
return;
b l i c
}
P u
ul
}
}
a h
Let’s understand the max heap through an example.
R
In the above figure, 55 is the parent node and it is greater than both of its child, and 11 is the parent
of 9 and 8, so 11 is also greater than from both of its child. Therefore, we can say that the above tree is a
max heap tree.
Insertion in the Heap tree
44, 33, 77, 11, 55, 88, 66
Suppose we want to create the max heap tree. To create the max heap tree, we need to consider
the following two cases:
First, we have to insert the element in such a way that the property of the complete binary tree must
be maintained.
Secondly, the value of the parent node should be greater than the either of its child.
Step 1: First we add the 44 element in the tree as shown below:
Step 2: The next element is 33. As we know that insertion in the binary tree always starts from the
left side so 44 will be added at the left of 33 as shown below:
315
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
a tio
As we can observe in the above figure that it
does not satisfy the property of the max heap
c
b l i because 44<88, so we will swap these two
values as shown below:
P u
Step 4: The next element is 11. The node
11 is added to the left of 33 as shown below:
Again, it is violating the max heap property
because 88>77 so we will swap these two
ul
values as shown below:
316
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Again, we will compare 15 with its child. Since 15 is greater than 10 so no swapping will occur.
Algorithm to heapify the tree
MaxHeapify(A, n, i)
{
int largest =i;
int l= 2i;
int r= 2i+1;
while(l<=n && A[l]>A[largest])
{
largest=l;
}
while(r<=n && A[r]>A[largest])
{
largest=r;
n s
}
if(largest!=i)
c a tio
{
b l i
swap(A[largest], A[i]);
heapify(A, n, largest);
P u
}}
a h
4.5.2 Implementation of Heap ul
R
Q26. Implement and build heap using an example
Ans :
A more common approach is to store the heap in an array. Since heap is always a complete binary
tree, it can be stored compactly. No space is required for pointers; instead, the parent and children of each
node can be found by simple arithmetic on array indices.
317
Rahul Publications
B.Sc. II YEAR III SEMESTER
This implementation is particularly useful in the heapsort algorithm, where it allows the space in the
input array to be reused to store the heap (i.e., the algorithm is in-place). However it requires allocating
the array before filling it, which makes this method not that useful in priority queues implementation,
where the number of elements is unknown.
It is perfectly acceptable to use a traditional binary tree data structure to implement a binary heap.
There is an issue with finding the adjacent element on the last level on the binary heap when adding an
element.
Building a Heap
A heap could be built by successive insertions. This approach requires O(n log n) time
for n elements. Why?
The optimal method:
Starts by arbitrarily putting the elements on a binary tree.
Starting from the lowest level and moving upwards until the heap property is restored by shifting
the root of the subtree downward as in the removal algorithm.
n s
If all the subtrees at some height h (measured from the bottom) have already been “heapified”, the
trees at hight h+1 can be heapified by sending their root down. This process takes O(h) swaps.
tio
As an example, let’s build a heap with the following values: 20, 35, 23, 22, 4, 45, 21, 5, 42 and 19.
c
Q27. Write about heap data structure
u b
Explain , what is heapify?
ul P OR
Ans :
318
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
319
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
7. Swap largest with currentElementSwap if necessary
c a tio
8.
Algorithm
b l i
Repeat steps 3-7 until the subtrees are also heapified.
Heapify(array, size, i)
P u
ul
set i as largest
h
leftChild = 2i + 1
a
R
rightChild = 2i + 2
if leftChild >array[largest]
set leftChildIndex as largest
if rightChild >array[largest]
set rightChildIndex as largest
swap array[i] andarray[largest]
4.5.3 Heap Sort
Q28. What is heap sort? Write the heap sort algorithm? Explain with an example.
Ans : (Dec.-18)
Heapsort is a popular and efficient sorting algorithm. The concept of heap sort is to eliminate the
elements one by one from the heap part of the list, and then insert them into the sorted part of the list.
Heapsort is the in-place sorting algorithm.
Algorithm
320
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
HeapSort(arr)
BuildMaxHeap(arr)
for i = length(arr) to 2
swap arr[1] with arr[i]
heap_size[arr] = heap_size[arr] ? 1
MaxHeapify(arr,1)
End
BuildMaxHeap(arr)
BuildMaxHeap(arr)
heap_size(arr)
= length(arr)
for i = length(arr)/2 to 1
MaxHeapify(arr,i)
n s
tio
End
MaxHeapify(arr,i)
MaxHeapify(arr,i)
l i c a
L = left(i)
u b
R = right(i)
ul P
if L ? heap_size[arr] and arr[L] > arr[i]
largest = L
else
a h
largest = i R
if R ? heap_size[arr] and arr[R] > arr[largest]
largest = R
if largest != i
swap arr[i] with arr[largest]
MaxHeapify(arr,largest)
End
Working of Heap sort Algorithm
In heap sort, basically, there are two phases involved in the sorting of elements. By using the heap
sort algorithm, they are as follows -
The first step includes the creation of a heap by adjusting the elements of the array.
After the creation of heap, now remove the root element of the heap repeatedly by shifting it to the
end of the array, and then store the heap structure with the remaining elements.
321
Rahul Publications
B.Sc. II YEAR III SEMESTER
Now let’s see the working of heap sort in detail by using an example. To understand it more clearly,
let’s take an unsorted array and try to sort it using heap sort. It will make the explanation clearer and
easier.
First, we have to construct a heap from the given array and convert it into max heap.
n s
c a tio
b l i
u
After converting the given heap into max heap, the array elements are -
P
a h ul
R
Next, we have to delete the root element (89) from the max heap. To delete this node, we have
to swap it with the last node, i.e. (11). After deleting the root element, we again have to heapify it to
convert it into max heap.
After swapping the array element 89 with 11, and converting the heap into max-heap, the elements
of array are -
322
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
In the next step, again, we have to delete the root element (81) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (54). After deleting the root element, we again have to
heapify it to convert it into max heap.
n s
c a tio
b l i
After swapping the array element 81 with 54 and converting the heap into max-heap, the
elements of array are -
P u
a h ul
R
In the next step, we have to delete the root element (76) from the max heap again. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have to
heapify it to convert it into max heap.
323
Rahul Publications
B.Sc. II YEAR III SEMESTER
After swapping the array element 76 with 9 and converting the heap into max-heap, the elements
of array are -
In the next step, again we have to delete the root element (54) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (14). After deleting the root element, we again have to
heapify it to convert it into max heap.
n s
c a tio
b l i
After swapping the array element 54 with 14 and converting the heap into max-heap, the
elements of array are -
P u
a h ul
R
In the next step, again we have to delete the root element (22) from the max heap. To delete this node,
we have to swap it with the last node, i.e. (11). After deleting the root element, we again have to heapify
it to convert it into max heap.
After swapping the array element 22 with 11 and converting the heap into max-heap, the
elements of array are -
324
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
In the next step, again we have to delete the root element (14) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have to
heapify it to convert it into max heap.
After swapping the array element 14 with 9 and converting the heap into max-heap, the elements
of array are -
n s
c a tio
i
In the next step, again we have to delete the root element (11) from the max heap. To delete this
u b l
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have to
ul P
a h
R
After swapping the array element 11 with 9, the elements of array are -
Now, heap has only one element left. After deleting it, heap will be empty.
325
Rahul Publications
B.Sc. II YEAR III SEMESTER
// To heapify a subtree rooted with node i which // call max heapify on the reduced heap
is heapify(arr, i, 0);
// an index in arr[]. n is size of heap }
n s
tio
void heapify(int arr[], int n, int i) }
l i a
/* A utility function to print array of size n */
c
void printArray(int arr[], int n)
int largest = i; // Initialize largest as root
u b
{
int l = 2 * i + 1; // left = 2*i + 1
ul
int r = 2 * i + 2; // right = 2*i + 2
P for (int i = 0; i < n; ++i)
cout << arr[i] << “ “;
R ah
// If left child is larger than root
// Driver program
largest = l;
int main()
// If right child is larger than largest so far
{
if (r < n && arr[r] > arr[largest])
int arr[] = { 12, 11, 13, 5, 6, 7 };
largest = r; int n = sizeof(arr) / sizeof(arr[0]);
// If largest is not root heapSort(arr, n);
326
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because
Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Following
are some uses other than Heapsort.
Priority Queues
Priority queues can be efficiently implemented using Binary Heap because it supports insert(),
delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci
Heap are variations of Binary Heap. These variations perform union also in O(logn) time which is a O(n)
operation in Binary Heap. Heap Implemented priority queues are used in Graph algorithms like Prim’s
Algorithm and Dijkstra’s algorithm.
Order statistics
n s
The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an
tio
array. See method 4 and 6 of this post for details.
l i c a
u b
ul P
a h
R
327
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
In this representation, graph can be represented using a matrix of size total number of vertices by
total number of vertices. That means if a graph with 4 vertices can be represented using a matrix of 4X4
class. In this matrix, rows and columns both represents vertices. This matrix is filled with either 1 or 0.
Here, 1 represents there is an edge from row vertex to column vertex and 0 represents there is no edge
from row vertex to column vertex.
For example, consider the following undirected graph representation...
n s
c a tio
b l i
Directed graph representation...
P u
a h ul
R
2. Adjacency List.
Ans :
In this representation, every vertex of graph contains list of its adjacent vertices.
For example, consider the following directed graph representation implemented using linked list...
328
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
n s
c a tio
b l i
P u
a h ul
R
In the above tree, the total edge weight is 10 which is less than the above spanning trees; therefore,
the minimum spanning tree is a tree which is having an edge weight, i.e., 10.
Properties of Spanning tree
A connected graph can contain more than one spanning tree. The spanning trees which are minimally
connected or we can say that the tree which is having a minimum total edge weight would be
considered as the minimum spanning tree.
All the possible spanning trees that can be created from the given graph G would have the same
number of vertices, but the number of edges in the spanning tree would be equal to the number of
vertices in the given graph minus 1.
The spanning tree does not contain any cycle. Let’s understand this property through an example.
4. What is Heap?
Ans :
A heap is a complete binary tree, and the binary tree is a tree in which the node can have utmost
two children. Before knowing more about the heap data structure, we should know about the complete
binary tree.
329
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
A fixed process converts a key to a hash key is known as a Hash Function.
This function takes a key and maps it to a value of a certain length which is called a Hash
value or Hash.
Hash value represents the original string of characters, but it is normally smaller than the original.
It transfers the digital signature and then both hash value and signature are sent to the receiver.
Receiver uses the same hash function to generate the hash value and then compares it to that
received with the message.
If the hash values are same, the message is transmitted without errors.
6. Min Heap
Ans :
The value of the parent node should be less than or equal to either of its children.
Or
n s
In other words, the min-heap can be defined as, for every node i, the value of node i is greater than
c a tio
or equal to its parent value except the root node. Mathematically, it can be defined as:
b l i
P u
a h ul
R
In the above figure, 11 is the root node, and the value of the root node is less than the value of all
the other nodes (left child or a right child).
7. Max Heap
Ans :
The value of the parent node is greater than or equal to its children.
Or
In other words, the max heap can be defined as for every node i; the value of node i is less than or
equal to its parent value except the root node. Mathematically, it can be defined as:
A[Parent(i)] >= A[i]
330
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
The above tree is a max heap tree as it satisfies the property of the max heap. Now, let’s see the
array representation of the max heap.
8. What is graph?
Ans :
n s
Graph is a non linear data structure, it contains a set of points known as nodes (or vertices) and set
tio
of links known as edges (or Arcs) which connects the vertices. A graph is defined as follows:
i a
Graph is a collection of vertices and arcs which connects vertices in the graph
c
Graph is a collection of nodes and edges which connects nodes in the graph
l
edges.
u b
Generally, a graph G is represented as G = ( V , E ), where V is set of vertices and E is set of
Example
ul P
The following is a graph with 5 vertices and 6 edges. This graph G can be defined as G = (V , E )
Where,
a h
R
V = {A,B,C,D,E} and
E = {(A,B),(A,C)(A,D),(B,D), (C,D),(B,E), (E,D)}.
331
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
When the two different values have the same value, then the problem occurs between the two
values, known as a collision. In the above example, the value is stored at index 6. If the key value is 26,
then the index would be:
h(26) = 26%10 = 6
Therefore, two values are stored at the same index, i.e., 6, and this leads to the collision problem.
To resolve these collisions, we have some techniques known as collision techniques.
The following are the collision techniques:
Open Hashing: It is also known as closed addressing.
Closed Hashing: It is also known as open addressing.
11. Heap as abstract data type.
Ans :
n s
tio
Heap data structure is a complete binary tree that satisfies the heap property, where any given
node is
i c a
Always greater than its child node/s and the key of the root node is the largest among all other
l
nodes. This property is also called max heap property.
u b
Always smaller than the child node/s and the key of the root node is the smallest among all other
12.
ul P
nodes. This property is also called min heap property.
What is Hashing? Define it with an example.
Ans :
a h
R
Hashing is the process of mapping large amount of data item to smaller table with the help of
hashing function.
Hashing is also known as Hashing Algorithm or Message Digest Function.
It is a technique to convert a range of key values into a range of indexes of an array.
It is used to facilitate the next level searching method when compared with the linear or binary
search.
Hashing allows to update and retrieve any data entry in a constant time O(1).
Constant time O(1) means the operation does not depend on the size of the data.
Hashing is used with a database to enable items to be retrieved more quickly.
It is used in the encryption and decryption of digital signatures.
Example
Consider an example of hash table of size 20, and the following items are to be stored. Item are in
the (key,value) format.
332
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
u37 % 20 = 17
b 17
ul P
a h
R
333
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s [b]
tio
(a) Insert Sort (b) Selection Sort
5.
(c) Quick Sort
Which of the following is not a stable Algorithm
(d) None
l i c a [b]
b
Pu
(a) Insertion Sort (b) Selection Sort
(c) Bubble Sort (d) Merge Sort
6.
ul
Finding the location of the elements with a given values is [b]
7.
(a) Traversal
(c) Sorting
R ah (b) Searching
(d) None
Which of the following is not a non-comparison sort [d]
(a) Counting Sort (b) Bucket Sort
(c) Radix Sort (d) Shell Sort
8. is putting an element in the appropriate place in a sorted list. [a]
(a) Insertion Sort (b) Extraction Sort
(c) Selection Sort (d) Merge Sort
9. Partition and Exchange sorting is [a]
(a) Quick Sort (b) Tree Sort
(c) Heap Sort (d) Bubble Sort
10. Which of the following sorting algorithm of priority queue uses [a]
(a) Bubble Sort (b) Insertion Sort
(c) Merge Sort (d) Selection Sort
334
Rahul Publications
UNIT - IV DATA STRUCTURES USING C++
9. As per ADT
n s
is a data type which stores a collection of elements.
c a tio
ANSWERS
b l i
1. Searching
P u
ul
2. Ordering /Arranging Data
3. Sub Array
a h
4.
5.
R
Divide and Conqure
Comparision
6. O(n2)
7. Binary Tree
8. Max Heap
9. Heap
335
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
A graph is defined as G = (V,E) where,
(i) V is the set of elements called nodes or vertices or points.
(ii) E is the set of edges of the graph identified with a unique pair (U, V) of nodes.
Here (U, V) pair denotes that there is an edge from node U to node V.
2. Define hashing.
Ans :
Hashing is a technique that makes use of a hash function for mapping pairs to the corresponding
(entries) positions in a hash table. Ideally a pair ‘P’ with a key ‘K’ is stored at a position f(K) by the hash
function ‘f’. Each hash table position can store one pair.
n s
tio
3. Define hash function.
Ans :
i c a
It is a function that is used to map the dictionary pairs to the corresponding entries in the hash table.
l
u
the pair “pair” is stored at f (key) position in a table. b
If the dictionary pair is ‘pair’ and if it consists of the key ‘key and if ‘/ denotes the hash function then
ul P
In order to search a pair with the key K, first we find f(K) and determine whether a pair is at f (K)
position in the hash table. If it is not present at f(K) then we insert the pair at f(K) else if it occurs f(K) then
h
we find the desired pair that can be deleted if required.
a
R
4. Define hash table.
Ans :
It is a data structure that is used to store dictionary pairs. It is of fixed size. The ‘search’ operation is
applied to a part of the dictionary pair called the key. The size of the hash table is represented by a variable
called the table size which ranges from q to (table size –1).
5. Define heap.
Ans :
A complete binary tree in which the value node is either greater than, lesser than or equal to values
in child nodes is called a heap.
Heap can be classified as,
(i) Ascending heap (min heap)
(ii) Descending heap (max heap)
336
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
Practicals
1. Write C++ programs to implement the following using an array
Ans :
Stack ADT
#include<iostream>
#include<conio.h>
using namespace std;
class Stack
{
int stk[10];
int top;
public:
n s
Stack()
{
c a tio
top=-1;
b l i
}
P u
ul
//This funtion is used to push an elemnt into stack
void push(int x)
{
a h
if(isFull())
{
R
cout<<"Stack is full";
return;
}
top++;
stk[top]=x;
cout<<"Inserted Element:"<<" "<<x;
}
//This functionn is used to check if the stack is full
bool isFull()
{
int size=sizeof(stk)/sizeof(*stk);
337
Rahul Publications
B.Sc. II YEAR III SEMESTER
if(top == size-1)
{
return true;
}
else
{
return false;
}
}
n s
tio
{
return true;
}
l i c a
else
u b
{
return false;
ul P
}
a h
}
R
//This function is used to pop an element of stack
void pop()
{
if(isEmpty())
{
cout<<"Stack is Empty";
return;
}
cout<<"Deleted element is:" <<" "<<stk[top--];
}
//This function is used to display the elements of the stack
void display()
338
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
{
if(top==-1)
{
cout<<" Stack is Empty!!";
return;
}
for(int i=top;i>=0;i--)
{
cout<<stk[i] <<" ";
}
}
};
void main()
n s
tio
{
int ch;
Stack st;
l i c a
while(1)
u b
{
ul P
cout<<"\n1.Push 2.Pop 3.Display 4.Exit\nEnter ur choice";
cin>> ch;
a h
switch(ch)
{ R
case 1: cout <<"Enter the element you want to push";
cin>> ch;
st.push(ch);
break;
case 2: st.pop();
break;
case 3: st.display();
break;
case 4: exit(0);
}
}
}
339
Rahul Publications
B.Sc. II YEAR III SEMESTER
Sample Output:
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to push 11
Inserted Element: 11
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to push 22
Inserted Element: 22
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to push 33
Inserted Element: 33
1.Push 2.Pop 3.Display 4.Exit
n s
tio
Enter ur choice 1
Enter the element you want to push 44
Inserted Element: 44
l i c a
1.Push 2.Pop 3.Display 4.Exit
u b
Enter ur choice 1
ul P
Enter the element you want to push 55
Inserted Element: 55
a h
Enter ur choice 3
55 44 33 22 11
R
1.Push 2.Pop 3.Display 4.Exit
b) Queue ADT
#include <iostream>
using namespace std;
const int Max=10;
void Qinsert(int Q[],int &R,int F)
{
if ((R+1)%Max!=F)
{
R=(R+1)%Max;
cout<<"Data:";
cin>>Q[R];
340
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
else
cout<<"Queue is Full!"<<endl;
}
void Qdelete(int Q[],int R,int &F)
{
if (R!=F)
{
F=(F+1)%Max;
cout<<Q[F]<<" Deleted!";
}
else
cout<<"Queue is empty"<<endl;
}
n s
tio
void Qdisplay(int Q[],int R,int F)
{
int Cn=F;
l i c a
while (Cn!=R)
u b
{
Cn=(Cn+1)%Max;
ul P
cout<<Q[Cn]<<endl;
a h
}
}
int main()
R
{ //Initialisation Steps
int Que[Max],Rear=0,Front=0;
char Ch;
do
{
cout<<"\n I:Insert/D:Delete/S:Show/Q:Quit ";
cin>>Ch;
switch(Ch)
{
case 'I':Qinsert(Que,Rear,Front);
break;
341
Rahul Publications
B.Sc. II YEAR III SEMESTER
case 'D':Qdelete(Que,Rear,Front);
break;
case 'S':Qdisplay(Que,Rear,Front);
break;
}
}while (Ch!='Q');
return 0 ;
}
Output:
I:Insert/D:Delete/S:Show/Q:Quit I
Data:10
I:Insert/D:Delete/S:Show/Q:Quit I
Data:20
I:Insert/D:Delete/S:Show/Q:Quit D
n s
10 Deleted!
I:Insert/D:Delete/S:Show/Q:Quit I
c a tio
Data:30
b l i
u
I:Insert/D:Delete/S:Show/Q:Quit I
P
ul
Data:40
I:Insert/D:Delete/S:Show/Q:Quit S
20
a h
30
40
R
I:Insert/D:Delete/S:Show/Q:Quit Q
...Program finished with exit code 0
Press ENTER to exit console.
2. Write a C++ program to implement Circular queue using array.
Ans :
/* Circular Queue */
#include<iostream>
#include<climits>
#define MAX 50
using namespace std;
// gloabal variables - queue_array, front, rear
342
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
int queue[MAX];
int front=-1,rear=-1;
// Utility to Enqueue an element to the Queue
void enqueue(int num)
{
if((rear==MAX-1 && front==0) || (front==rear+1))
{
cout<<"Queue is Full !!\n";
return;
}
if(rear == MAX-1) // front != 0
rear = -1;
rear++;
queue[rear] = num;
n s
tio
if(front == -1)
}
front=0;
l i c a
// Utility to Dequeue an element from Queue
u b
void dequeue()
{
ul P
if(front==-1)
a h
{
R
cout<<"Queue is Empty !!\n";
return;
}
int number;
number = queue[front];
queue[front] = INT_MAX;
if(front == rear)
{
front = -1;
rear = -1;
}
else if(front == MAX-1) //rear != MAX-1
343
Rahul Publications
B.Sc. II YEAR III SEMESTER
front = 0;
else
front++;
n s
tio
cout<<"Front of the queue = "<<queue[front]<<"\n";
}
// Utility to display Rear of Queue
l i c a
void queue_rear()
u b
{
if(rear == -1)
ul P
{
a h
}
R
cout<<"Queue is Empty !!\n";
return;
344
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
for(i=0;i<MAX;i++)
{
if(queue[i] == INT_MAX)
continue;
cout<<queue[i]<<" ";
}
cout<<"\n";
}
// Driver Code
int main()
{
int optn,number;
for(int i=0;i<MAX;i++)
n s
queue[i] = INT_MAX;
while(1)
c a tio
{
b l i
u
cout<<"\nOperations available : \n";
P
ul
cout<<"1. ENQUEUE\n2. DEQUEUE\n3. Front\n4. Rear\n5. DISPLAY queue\n6. Exit\n\n";
cout<<"Enter your choice : ";
a h
cin>>optn;
{
R
switch(optn)
case(1):
cout<<"Enter the number : ";
cin>>number;
enqueue(number);
break;
case(2):
dequeue();
break;
case(3):
queue_front();
break;
345
Rahul Publications
B.Sc. II YEAR III SEMESTER
case(4):
queue_rear();
break;
case(5):
disp_queue();
break;
case(6):
exit(0);
}
}
return 0;
}
Output :
Operations available :
n s
tio
1. ENQUEUE
2. DEQUEUE
3. Front
l i c a
4. Rear
u b
5. DISPLAY queue
6. Exit
ul P
Enter your choice : 1
a h
R
Enter the number : 12
Operations available :
1. ENQUEUE
2. DEQUEUE
3. Front
4. Rear
5. DISPLAY queue
6. Exit
Enter your choice : 1
Enter the number : 13
Operations available :
1. ENQUEUE
2. DEQUEUE
3. Front
346
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
4. Rear
5. DISPLAY queue
6. Exit
Enter your choice : 1
Enter the number : 14
Operations available :
1. ENQUEUE
2. DEQUEUE
3. Front
4. Rear
5. DISPLAY queue
6. Exit
Enter your choice : 5
12 13 14
n s
3.
Ans :
c a tio
Write C++ programs to implement the following using a single linked list.
Stack ADT
b l i
#include <iostream>
P u
ul
#include <string.h>
usingnamespace std;
struct Node{
a h
int stu_no;
char stu_name[50];
R
int p;
Node *next;
};
Node *top;
class stack{
public:
void push(int n,char name[],int perc);
void pop();
void display();
};
void stack :: push(int n,char name[],int perc)
347
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
struct Node *newNode=new Node;
//fill data part
newNode->stu_no=n;
newNode->p=perc;
strcpy(newNode->stu_name,name);
//link part
newNode->next=top;
//make newnode as top/head
top=newNode;
}
void stack ::pop()
s
{
if(top==NULL){
cout<<"List is empty!"<<endl;
tio n
return;
l i c a
}
u b
cout<<top->stu_name<<" is removed."<<endl;
top=top->next;
}
ul P
void stack:: display()
a h
{
if(top==NULL){
R
cout<<"List is empty!"<<endl;
return;
}
struct Node *temp=top;
while(temp!=NULL){
cout<<temp->stu_no<<" ";
cout<<temp->stu_name<<" ";
cout<<temp->p<<" ";
cout<<endl;
temp=temp->next;
}
348
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
cout<<endl;
}
int main(){
stack s;
char ch;
do{
int n;
cout<<"ENTER CHOICE\n"<<"1.Push\n"<<"2.Pop\n"<<"3.Display\n";
cout<<"Make a choice: ";
cin>>n;
switch(n){
case1:
Node n;
n s
cout<<"Enter details of the element to be pushed : \n";
cout<<"Roll Number : ";
c a tio
cin>>n.stu_no;
b l i
cout<<"Enter Name: ";
P u
ul
std::cin.ignore(1);
cin.getline(n.stu_name,50);
a h
cout<<"Enter Percentage: ";
cin>>n.p;
R
//push data into the stack
s.push(n.stu_no,n.stu_name,n.p);
break;
case2 :
//pop data from stack
s.pop();
break;
case3 :
//display data
s.display();
break;
default :
349
Rahul Publications
B.Sc. II YEAR III SEMESTER
cout<<"Invalid Choice\n";
}
cout<<"Do you want to continue ? : ";
cin>>ch;
}while(ch=='Y'||ch=='y');
return 0;
}
OUTPUT
R CHOICE
1. Push
2. Pop
3.Display
Make a choice: 1
Enter details of the element to be pushed :
n s
tio
Roll Number : 101
Enter Name: PRIYA
Enter Percentage: 99
l i c a
Do you want to continue ? : y
u b
ENTER CHOICE
1.Push
ul P
2.Pop
a h
3.Display
Make a choice: 1 R
Enter details of the element to be pushed :
Roll Number : 102
Enter Name: Mahak
Enter Percentage: 95
Do you want to continue ? : y
ENTER CHOICE
1.Push
2.Pop
3.Display
Make a choice: 3
102 Mahak 95
101 PRIYA 99
350
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
b) Queue ADT
#include<iostream>
usingnamespace std;
struct Node{
int data;
Node *next;
};
class Queue{
public:
Node *front,*rear;
Queue(){front=rear=NULL;}
void insert(int n);
s
void deleteitem();
void display();
~Queue();
tio n
};
l i c a
void Queue::insert(int n){
Node *temp=new Node;
u b
if(temp==NULL){
cout<<"Overflow"<<endl;
ul P
return;
a h
}
temp->data=n;
R
temp->next=NULL;
//for first node
if(front==NULL){
front=rear=temp;
}
else{
rear->next=temp;
rear=temp;
}
cout<<n<<" has been inserted successfully."<<endl;
}
351
Rahul Publications
B.Sc. II YEAR III SEMESTER
void Queue::display(){
if(front==NULL){
cout<<"Underflow."<<endl;
return;
}
Node *temp=front;
//will check until NULL is not found
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
void Queue :: deleteitem()
n s
tio
{
if (front==NULL){
cout<<"underflow"<<endl;
l i c a
return;
u b
}
ul P
cout<<front->data<<" is being deleted "<<endl;
h
if(front==rear)//if only one node is there
a
front=rear=NULL;
else
front=front->next;
R
}
Queue ::~Queue()
{
while(front!=NULL)
{
Node *temp=front;
front=front->next;
delete temp;
}
rear=NULL;
}
352
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
int main(){
Queue Q;
Q.display();
Q.insert(10);
Q.insert(24);
Q.insert(28);
Q.insert(32);
Q.insert(30);
Q.display();
Q.deleteitem();
Q.deleteitem();
Q.deleteitem();
Q.deleteitem();
Q.deleteitem();
return 0;
n s
}
Output
c a tio
Underflow.
b l i
10 has been inserted successfully.
P u
ul
24 has been inserted successfully.
28 has been inserted successfully.
a h
32 has been inserted successfully.
R
30 has been inserted successfully.
10 24 28 32 30
10 is being deleted
24 is being deleted
28 is being deleted
32 is being deleted
30 is being deleted
4. Write a C++ program to implement Circular queue using Single linked list.
Ans :
#include <iostream>;
using namespace std;
class Queue {
public:
353
Rahul Publications
B.Sc. II YEAR III SEMESTER
};
void displayQueue();
n s
/* Function to create Circular queue */
void Queue::enQueue(int elem)
c a tio
{
b l i
u
if ((front == 0 && rear == size-1) || (rear == (front-1)%(size-1))) {
P
ul
cout<<"\nQueue is Full";
return;
}
a h
R
else if (front == -1) {
front = rear = 0;
/* Insert First Element */
circular_queue[rear] = elem;
}
else if (rear == size-1 && front != 0) {
rear = 0;
circular_queue[rear] = elem;
}
else {
rear++;
circular_queue[rear] = elem;
}
}
354
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
n s
tio
front = 0;
else
front++;
l i c a
return data;
u b
}
//display elements of Circular Queue
ul P
void Queue::displayQueue()
a h
{
if (front == -1) {R
cout<<"\nQueue is Empty"<<endl;
return;
}
cout<<"\nCircular Queue elements: ";
if (rear >= front) {
for (int i = front; i <= rear; i++)
cout<<circular_queue[i]<<" ";
}
Else {
for (int i = front; i < size; i++)
cout<<circular_queue[i]<<" ";
for (int i = 0; i <= rear; i++)
355
Rahul Publications
B.Sc. II YEAR III SEMESTER
cout<<circular_queue[i]<<" ";
}
}
//main program
int main()
{
Queue pq(5);
// Insert elements in Circular Queue
pq.enQueue(2);
pq.enQueue(4);
pq.enQueue(6);
pq.enQueue(8);
// Display elements present in Circular Queue
n s
pq.displayQueue();
// Delete elements from Circular Queue
c a tio
l
cout<<"\nElement Dequeued = "<<pq.deQueue();
b i
u
cout<<"\nElement Dequeued = "<<pq.deQueue();
P
ul
pq.displayQueue();
pq.enQueue(10);
pq.enQueue(12);
a h
pq.enQueue(14);
R
pq.displayQueue();
pq.enQueue(10);
return 0;
}
Output:
Circular Queue elements: 2 4 6 8
Element Dequeued = 2
Element Dequeued = 4
Circular Queue elements: 6 8
Circular Queue elements: 6 8 10 12 14
Queue is Full
356
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
5. Write a C++ program to implement the double ended queue ADT using double linked
list.
Ans :
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:
int data;
class node *next;
class node *prev;
};
n s
class dqueue: public node
{
c a tio
node *head,*tail;
b l i
int top1,top2;
P u
ul
public:
dqueue()
{
a h
top1=0;
top2=0;
R
head=NULL;
tail=NULL;
}
void push(int x)
{
node *temp;
int ch;
if(top1+top2 >=5)
{
cout <<"dqueue overflow";
return ;
357
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
if( top1+top2 == 0)
{
head = new node;
head->data=x;
head->next=NULL;
head->prev=NULL;
tail=head;
top1++;
}
else
{
cout <<" Add element 1.FIRST 2.LAST\n Enter Your Choice:";
cin >> ch;
n s
if(ch==1)
{
c a tio
top1++;
b l i
temp=new node;
P u
ul
temp->data=x;
temp->next=head;
a h
temp->prev=NULL;
R
head->prev=temp;
head=temp;
}
else
{
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
}
358
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
}
void pop()
{
int ch;
cout <<"Delete 1.First Node 2.Last Node\n Enter Your Choice:";
cin >>ch;
if(top1 + top2 <=0)
{
cout <<"\nDqueue under flow";
return;
}
if(ch==1)
{
n s
head=head->next;
head->prev=NULL;
c a tio
top1--;
b l i
}
P u
ul
else
{
top2--;
a h
R
tail=tail->prev;
tail->next=NULL;
}
}
void display()
{
int ch;
node *temp;
cout <<"Display From 1.STARTING 2.ENDING\n Enter Your Choice";
cin >>ch;
if(top1+top2 <=0)
{
cout <<"under flow";
359
Rahul Publications
B.Sc. II YEAR III SEMESTER
return ;
}
if (ch==1)
{
temp=head;
while(temp!=NULL)
{
cout << temp->data <<" ";
temp=temp->next;
}
}
else
{
temp=tail;
n s
while( temp!=NULL)
{
c a tio
cout <<temp->data << " ";
b l i
temp=temp->prev;
P u
ul
}
}
}
a h
};
int main()
R
{
dqueue d1;
int ch;
while (1)
{
cout <<"1.INSERT 2.DELETE 3.DISPLAY 4.EXIT\n Enter Your Choice:";
cin >>ch;
switch(ch)
{
case 1:
cout <<"Enter the Element: ";
360
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
}<br> return 0;
n s
OUTPUT:
1.INSERT 2.DELETE 3.DISPLAY 4.EXIT
c a tio
Enter Your Choice:1
b l i
Enter the Element: 10
P u
ul
1.INSERT 2.DELETE 3.DISPLAY 4.EXIT
Enter ur choice:1
Enter the Element: 15
a h
R
Add element 1.FIRST 2.LAST
Enter Your Choice:2
1.INSERT 2.DELETE 3.DISPLAY 4.EXIT
Enter Your Choice:3
Display From 1.STARTING 2.ENDING
Enter Your Choice:1
10 15 1.INSERT 2.DELETE 3.DISPLAY 4.EXIT
Enter Your Choice:4
6. Write a C++ program to solve tower of Hanoi problem recursively
Ans :
#include<iostream>
usingnamespace std;
//tower of HANOI function implementation
361
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
//calling the TOH
P u
ul
TOH(n,'A','B','C');
return 0;
}
a h
Output
Enter no. of disks:3
R
Move Disk 1 from A to C
Move Disk 2 from A to B
Move Disk 1 from C to B
Move Disk 3 from A to C
Move Disk 1 from B to A
Move Disk 2 from B to C
Move Disk 1 from A to C
7. Write C++ program to perform the following operations:
Ans :
Insert an element into a binary search tree.
#include<iostream>
362
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
usingnamespace std;
template<classt>
classbst
{
struct NODE
{
t data;
NODE* left, *right;
};
public:
NODE* createnewnode(t data)
{
NODE* createnewnode = newNODE();
createnewnode->data = data;
n s
createnewnode->left = createnewnode->right = NULL;
return createnewnode;
c a tio
}
b l i
NODE* Insert(NODE* root,t data)
P u
ul
{
if(root == NULL)
{
a h
R
root = createnewnode(data);
}
elseif(data <= root->data)
{
root->left = Insert(root->left,data);
}
else
{
root->right = Insert(root->right,data);
}
return root;
}
voidinorder(NODE* root )
363
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
if(root != NULL)
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
bst()
{
NODE* root = NULL;
t a,b,c,d,e,f;
cout<<endl<<"Enter the data"<<endl;
cin>>a;
n s
cin>>b;
cin>>c;
c a tio
cin>>d;
b l i
cin>>e;
P u
ul
cin>>f;
root = Insert(root,a);
a h
root = Insert(root,b);
R
root = Insert(root,c);
root = Insert(root,d);
root = Insert(root,e);
root = Insert(root,f);
cout<<"***THE BINARY SEARCH TREE*** "<<endl;
cout<<"Inorder:";
inorder(root);
cout<<endl;
insertion(root);
}
NODE* insertion(NODE* root)
{
t n;
364
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
b l i
12
P u
ul
15
16
13
a h
R
***THE BINARY SEARCH TREE***
Inorder:12 13 15 16 25 31
Enter the ELEMENT to be inserted in the BST
17
***THE BINARY SEARCH TREE(2)***
Inorder:12 13 15 16 17 25 31
Enter the data
g
u
q
i
***THE BINARY SEARCH TREE***
Inorder: a g i q t u
365
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
struct node* getNode(int data)
b l i
{
P u
ul
node* newNode=new node();
newNode->data=data;
a h
newNode->left=NULL;
R
newNode->right=NULL;
return newNode;
}
void inorder(struct node* root)
{
if (root != NULL)
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
node* findMin(node*root)
366
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
{
while(root->left!=NULL)
{
root=root->left;
}
return root;
}
struct node* Insert(struct node* root, int data)
{
if (root == NULL)
return getNode(data);
if (data < root->data)
root->left = Insert(root->left, data);
elseif (data > root->data)
n s
root->right = Insert(root->right, data);
return root;
c a tio
}
b l i
bool Search(node*root,int value)
P u
ul
{
if(root==NULL)
a h
returnfalse;
R
elseif(root->data == value)
{
returntrue;
}
elseif(value < root-> data)
Search(root->left,value);
elseif(value > root->data)
Search(root->right,value);
}
node* Delete( node* root,int value)
{
c=Search(root,value);
if(root==NULL)
367
Rahul Publications
B.Sc. II YEAR III SEMESTER
return root;
elseif(value< root->data)
{
root->left= Delete(root->left,value);
}
elseif(value> root->data)
{
root->right= Delete(root->right,value);
}
// Node deletion
else
{
//case 1: Leaf Node
if(root->left==NULL&&root->right==NULL)
n s
{
delete root;
c a tio
root=NULL;
b l i
return root;
P u
ul
}
//case 2: one child
a h
elseif(root->left==NULL)
{
R
struct node* temp=root;
root=root->right;
delete temp;
return root;
}
elseif(root->right==NULL)
{
struct node* temp=root;
root=root->left;
delete temp;
return root;
}
368
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
//case 3: 2 child
else
{
struct node*temp=findMin(root->right);
root->data=temp->data;
root->right=Delete(root->right,temp->data);
}
}
return root;
}
int main()
{
node* root=NULL;
root=Insert(root,20);
n s
tio
Insert(root,15);
Insert(root,25);
Insert(root,18);
l i c a
Insert(root,10);
u b
Insert(root,16);
Insert(root,19);
ul P
Insert(root,17);
a h
R
cout<<"Before Deletion: "<<endl;
cout<<"Inorder: ";
inorder(root);
cout<<endl<<endl;
Delete(root,15);
if(c)
{
cout<<"Node Deleted"<<endl;
cout<<"\nAfter Deletion: "<<endl;
cout<<"Inorder: ";
inorder(root);
cout<<endl;
}
else
369
Rahul Publications
B.Sc. II YEAR III SEMESTER
return 0;
}
Output
Before Deletion:
Inorder: 10 15 16 17 18 19 20 25
Node Deleted
After Deletion:
Inorder: 10 16 17 18 19 20 25
c) Search for a key in a binary search tree.
#include <iostream>
using namespace std;
// Data structure to store a BST node
n s
tio
struct Node
{
int data;
l i c a
Node* left = nullptr, *right = nullptr;
u b
Node() {}
Node(int data): data(data) {}
ul P
};
a h
R
// Recursive function to insert a key into a BST
Node* insert(Node* root, int key)
{
// if the root is null, create a new node and return it
if (root == nullptr) {
return new Node(key);
}
// if the given key is less than the root node, recur for the left subtree
if (key < root->data) {
root->left = insert(root->left, key);
}
// if the given key is more than the root node, recur for the right subtree
else {
root->right = insert(root->right, key);
370
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
return root;
}
// Recursive function to search in a given BST
void search(Node* root, int key, Node* parent)
{
// if the key is not present in the key
if (root == nullptr)
{
cout << "Key not found";
return;
}
// if the key is found
if (root->data == key)
n s
tio
{
if (parent == nullptr) {
l i c a
cout << "The node with key " << key << " is root node";
}
u b
else if (key < parent->data)
{
ul P
h
cout << "The given key is the left node of the node with key "
a
}
else {
R
<< parent->data;
cout << "The given key is the right node of the node with key "
<< parent->data;
}
return;
}
// if the given key is less than the root node, recur for the left subtree;
// otherwise, recur for the right subtree
if (key < root->data) {
search(root->left, key, root);
} else {
371
Rahul Publications
B.Sc. II YEAR III SEMESTER
c a tio
Write C++ programs for the implementation tree traversal technique BFS.
Ans :
b l i
#include <iostream>
P u
ul
#include <conio.h>
usingnamespace std;
int c =0, t =0;
a h
struct node_info
{
R
int no;
int st_time;
}*q =NULL, *r =NULL, *x =NULL;
struct node
{
node_info *pt;
node*next;
}*front =NULL, *rear =NULL, *p =NULL, *np =NULL;
void push(node_info *ptr)
{
np=new node;
372
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
np->pt = ptr;
np->next =NULL;
if(front ==NULL)
{
front= rear = np;
rear->next =NULL;
}
else
{
rear->next = np;
rear= np;
rear->next =NULL;
}
}
n s
tio
node_info *remove()
{
if(front ==NULL)
l i c a
{
u b
cout<<"empty queue\n";
}
ul P
else
a h
{
p = front;
x = p->pt;
R
front= front->next;
delete(p);
return(x);
}
}
void bfs(int*v,int am[][7],int i)
{
if(c ==0)
{
q =new node_info;
q->no = i;
373
Rahul Publications
B.Sc. II YEAR III SEMESTER
q->st_time = t++;
cout<<"time of visitation for node "<<q->no<<":"<<q->st_time<<"\n\n";
v[i]=1;
push(q);
}
c++;
for(int j =0; j <7; j++)
{
if(am[i][j]==0||(am[i][j]==1&& v[j]==1))
continue;
elseif(am[i][j]==1&& v[j]==0)
{
r =new node_info;
n s
tio
r->no = j;
r->st_time = t++;
i c a
cout<<"time of visitation for node "<<r->no<<":"<<r->st_time<<"\n\n";
l
v[j]=1;
u b
push(r);
}
ul P
}
a h
remove();
R
if(c <=6&& front !=NULL)
bfs(v, am, remove()->no);
}
int main()
{
int v[7], am[7][7];
for(int i =0; i <7; i++)
v[i]=0;
for(int i =0; i <7; i++)
{
cout<<"enter the values for adjacency matrix row:"<<i+1<<endl;
for(int j =0; j <7; j++)
374
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
{
cin>>am[i][j];
}
}
bfs(v, am, 0);
getch();
}
Output
enter the values for adjacency matrix row:1
0
1
1
0
0
n s
tio
1
1
enter the values for adjacency matrix row:2
l i c a
1
u b
0
0
ul P
0
a h
0
0
0
R
enter the values for adjacency matrix row:3
1
0
0
0
0
0
1
time of visitation for node 0:0
time of visitation for node 1:1
time of visitation for node 2:2
375
Rahul Publications
B.Sc. II YEAR III SEMESTER
9. Write a C++ program that uses recursive functions to traverse a binary search tree.
Ans :
a) Pre-order
b) In-order
c) Post-order
// C++ program for different tree traversals
#include <iostream>
using namespace std;
/* A binary tree node has data, pointer to left childand a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
n s
this->data = data;
c a tio
i
left = right = NULL;
};
}
u b l
ul P
/* Given a binary tree, print its nodes according to the
a h
"bottom-up" postorder traversal. */
void printPostorder(struct Node* node)
{
if (node == NULL)
R
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
cout << node->data << " ";
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct Node* node)
{
376
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
cout << node->data << " ";
/* now recur on right child */
printInorder(node->right);
}
/* Given a binary tree, print its nodes in preorder*/
void printPreorder(struct Node* node)
{
if (node == NULL)
return;
n s
tio
/* first print data of node */
cout << node->data << " ";
/* then recur on left subtree */
l i c a
printPreorder(node->left);
u b
/* now recur on right subtree */
printPreorder(node->right);
ul P
}
a h
int main()
{
R
/* Driver program to test above functions*/
377
Rahul Publications
B.Sc. II YEAR III SEMESTER
return 0;
}
Output:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231
10. Write a C++ program to find height of a tree.
Ans :
#include <iostream>
using namespace std;
// Data structure to store a Binary Tree node
n s
struct Node
c a tio
i
{
int key;
Node *left, *right;
u b l
ul P
h
Node(int key)
{
this->key = key;
R a
this->left = this->right = NULL;
}
};
// Recursive function to calculate height of given binary tree
int height(Node* root)
{
// Base case: empty tree has height 0
if (root == NULL)
return 0;
// recur for left and right subtree and consider maximum depth
return 1 + max(height(root->left), height(root->right));
}
378
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
// main function
int main()
{
Node* root = NULL;
root = new Node(10);
root->left = new Node(1);
root->right = new Node(25);
root->left->left = new Node(9);
root->left->right = new Node(10);
root->right->left = new Node(13);
root->right->right = new Node(20);
cout<< "The height of the binary tree is " << height(root);
return 0;
}
n s
Output :
The height of binary tree is 3.
c a tio
11
l i
Write a C++ program to find MIN and MAX element of a BST.
b
Ans :
P u
ul
#include<iostream>
h
using namespace std;
struct BSTNode
{
R a
int data;
BSTNode *left;
BSTNode *right;
};
BSTNode* getnewnode(int data)
{
BSTNode* temp=new BSTNode();
temp->data=data;
temp->left=temp->right=NULL;
return temp;
}
BSTNode* insertnode(struct BSTNode *root,int data)
379
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
if(root==NULL)
{
root=getnewnode(data);
}
else if(data<=root->data)
{
root->left=insertnode(root->left,data);
}
else
{
root->right=insertnode(root->right,data);
s
}
return root;
}
tio n
bool search(BSTNode *root,int data)
l i c a
{
if(root==NULL) return false;
u b
ul
else if(root->data==data) return true;
else if(data<root->data)
P
a h
return search(root->left,data);
else
R
return search(root->right,data);
}
void preorder(BSTNode* root)
{
if(root==NULL)
return ;
else
{
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
380
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
void inorder(BSTNode* root)
{
if(root==NULL)
return ;
else
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
void postorder(BSTNode* root)
{
n s
if(root==NULL)
return ;
c a tio
else
b l i
{
P u
ul
postorder(root->left);
postorder(root->right);
a h
cout<<root->data<<" ";
}
}
R
int findmin(BSTNode* root) //itterative method
{
if(root==NULL)
{
cout<<"\nerror: tree is empty ";
return -1;
}
BSTNode* current=root;
while(current->left)
current=current->left;
return current->data;
381
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
int findmax(BSTNode* root) //itterative method find the maximum element
{
if(root==NULL)
{
cout<<"\n error: tree is empty ";
return -1;
}
BSTNode* current=root;
while(current->right)
current=current->right;
return current->data;
}
int recursive_findMin(BSTNode* root)
n s
{
if(root==NULL)
c a tio
{
b l i
cout<<"\n error: tree is empty ";
P u
ul
return -1;
}
a h
else if(root->left==NULL)
return root->data;
R
return recursive_findMin(root->left);
}
int recursive_findMax(BSTNode *root)
{
if(root==NULL)
{
cout<<"\n error: tree is empty ";
return -1;
}
else if(root->right==NULL)
return root->data;
return recursive_findMax(root->right);
382
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
int findHeight(BSTNode* root)
{
if(root==NULL)
return -1;
return max(findHeight(root->left),findHeight(root->right))+1;
}
int main()
{
int x;
struct BSTNode* root=NULL;
root=insertnode(root,10);
root=insertnode(root,15);
root=insertnode(root,9);
n s
tio
root=insertnode(root,8);
root=insertnode(root,7);
root=insertnode(root,6);
l i c a
cout<<"enter the data to search ";
u b
cin>>x;
if(search(root,x)==true)
ul P
h
cout<<"\n data is found ";
a
else
R
cout<<"\n data is not found";
cout<<"\npreorder traversal ";
preorder(root);
cout<<"\ninorder traversal ";
inorder(root);
cout<<"\npostorder traversal ";
postorder(root);
cout<<"\n height of tree= "<<findHeight(root);
cout<<"\n minimum element by itterative method: "<<findmin(root);
cout<<"\n maximum element by itterative method: "<<findmax(root);
cout<<"\n maximum element by recursive method : "<< recursive_findMax(root);
return 0;
}
383
Rahul Publications
B.Sc. II YEAR III SEMESTER
Output:-
enter the data to search 15
data Is found
preorder traversal 10 9 8 7 6 15
inorder traversal 6 7 8 9 10 15
postorder traversal 6 7 8 9 15 10
height of tree= 4
minimum element by itterative method: 6
maximum element by itterative method: 15
minimum element by recursive method : 6
maximum element by recursive method : 15
Process exited after 9.164 seconds with return value 0
Press any key to continue ...
12 Write a C++ program to find Inorder Successor of a given node.
n s
Ans :
#include <iostream>
c a tio
using namespace std;
b l i
// Data structure to store a BST node
P u
ul
struct Node
{
int data;
a h
R
Node* left = nullptr, *right = nullptr;
Node() {}
Node(int data): data(data) {}
};
// Recursive function to insert a key into a BST
Node* insert(Node* root, int key)
{
// if the root is null, create a new node and return it
if (root == nullptr) {
return new Node(key);
}
// if the given key is less than the root node, recur for the left subtree
if (key < root->data) {
384
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
s
root = root->left;
}
return root;
tio n
}
l i c a
u b
// Recursive function to find an inorder successor for the given key in a BST.
// Note that successor `succ` is passed by reference to the function
ul P
Node* findSuccessor(Node* root, Node* succ, int key)
{
// base case
a h
R
if (root == nullptr) {
return succ;
}
// if a node with the desired value is found, the successor is the minimum value
// node in its right subtree (if any)
if (root->data == key)
{
if (root->right != nullptr) {
return findMinimum(root->right);
}
}
// if the given key is less than the root node, recur for the left subtree
else if (key < root->data)
385
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
// update successor to the current node before recursing in the left subtree
succ = root;
return findSuccessor(root->left, succ, key);
}
// if the given key is more than the root node, recur for the right subtree
else {
return findSuccessor(root->right, succ, key);
}
return succ;
}
int main()
s
{
int keys[] = { 15, 10, 20, 8, 12, 16, 25 };
tio n
/* Construct the following tree
l i c a
/
15
\
u b
/
10
\
20
ul P
/\ / \
a h
/ \
8
/
12 16
\
R
25
*/
Node* root = nullptr;
for (int key: keys) {
root = insert(root, key);
}
386
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
cout << "The successor of node " << key << " is " << succ->data;
}
else {
cout << "No Successor exists for node " << key;
}
cout << endl;
}
return 0;
}
Output:
The successor of node 15 is 16
The successor of node 10 is 12
The successor of node 20 is 25
The successor of node 8 is 10
n s
The successor of node 12 is 15
The successor of node 16 is 20
c a tio
No Successor exists for node 25
b l i
13.
Ans : u
Write C++ programs to perform the following operations on B-Trees and AVL Trees.
P
a) Insertion b) Deletion
#include<iostream>
a h ul
#include<stdlib.h>
using namespace std;
R
#define TRUE 1
#define FALSE 0
#define NULL 0
class AVL;
class AVLNODE
{
friend class AVL;
private:
int data;
AVLNODE *left,*right;
int bf;
387
Rahul Publications
B.Sc. II YEAR III SEMESTER
};
class AVL
{
private:
AVLNODE *root;
public:
AVLNODE *loc,*par;
AVL()
{
root=NULL;
}
int insert(int);
s
void displayitem();
void display(AVLNODE *);
void removeitem(int);
tio n
void remove1(AVLNODE *,AVLNODE *,int);
l i c a
void remove2(AVLNODE *,AVLNODE *,int);
void search(int x);
u b
};
void search1(AVLNODE *,int);
ul P
int AVL::insert(int x)
a h
{
R
AVLNODE *a,*b,*c,*f,*p,*q,*y,*clchild,*crchild;
int found,unbalanced;
int d;
if(!root) //special case empty tree
{
y=new AVLNODE;
y->data=x;
root=y;
root->bf=0;
root->left=root->right=NULL;
return TRUE;
}
388
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
//phase 1:locate insertion point for x.a keeps track of the most
// recent node with balance factor +/-1,and f is the parent of a
// q follows p through the tree.
f=NULL;
a=p=root;
q=NULL;
found=FALSE;
while(p&&!found)
{
//search for insertion point for x
if(p->bf)
{
s
a=p;
}
f=q;
tio n
if(x<p->data) //take left branch
l i c a
{
q=p;
u b
}
p=p->left;
ul P
a h
else if(x>p->data)
{
q=p;
R
p=p->right;
}
else
{
y=p;
found=TRUE;
}
} //end while
//phase 2:insert and rebalance.x is not in the tree and
// may be inserted as the appropriate child of q.
if(!found)
389
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
y = new AVLNODE;
y->data=x;
y->left=y->right=NULL;
y->bf=0;
if(x<q->data) //insert as left child
q->left=y;
else
q->right=y; //insert as right child
//adjust balance factors of nodes on path from a to q
//note that by the definition of a,all nodes on this
//path must have balance factors of 0 and so will change
s
//to +/- d=+1 implies that x is inserted in the left
// subtree of a d=-1 implies
//to that x inserted in the right subtree of a.
tio n
if(x>a->data)
l i c a
{
p=a->right;
u b
b=p;
d=-1;
ul P
}
a h
else
{
R
p=a->left;
b=p;
d=1;
}
while(p!=y)
if(x>p->data) //height of right increases by 1
{
p->bf=-1;
p=p->right;
}
else //height of left increases by 1
390
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
{
p->bf=1;
p=p->left;
}
//is tree unbalanced
unbalanced=TRUE;
if(!(a->bf)||!(a->bf+d))
{
//tree still balanced
a->bf+=d;
unbalanced=FALSE;
}
if(unbalanced) //tree unbalanced,determine rotation type
{
n s
tio
if(d==1)
{
//left imbalance
l i c a
if(b->bf==1) //rotation type LL
u b
{
a->left=b->right;
ul P
h
b->right=a;
a
}
R
a->bf=0;
b->bf=0;
391
Rahul Publications
B.Sc. II YEAR III SEMESTER
b->bf=0;
break;
case -1:
b->bf=1; //LR(c)
a->bf=0;
break;
case 0:
b->bf=0; //LR(a)
a->bf=0;
break;
}
c->bf=0;
s
b=c; //b is the new root
} //end of LR
} //end of left imbalance
tio n
else //right imbalance
l i c a
{
u
if(b->bf==-1) //rotation type RR b
{
a->right=b->left;
ul P
a h
b->left=a;
R
a->bf=0;
b->bf=0;
}
else //rotation type LR
{
c=b->right;
b->right=c->left;
a->right=c->left;
c->right=b;
c->left=a;
switch(c->bf)
{
case 1:
392
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
a->bf=-1; //LR(b)
b->bf=0;
break;
case -1:
b->bf=1; //LR(c)
a->bf=0;
break;
case 0:
b->bf=0; //LR(a)
a->bf=0;
break;
}
c->bf=0;
b=c; //b is the new root
n s
}
} //end of LR
c a tio
b l i
//subtree with root b has been rebalanced and is the new subtree
if(!f)
P u
ul
root=b;
else if(a==f->left)
f->left=b;
a h
R
else if(a==f->right)
f->right=b;
} //end of if unbalanced
return TRUE;
} //end of if(!found)
return FALSE;
} //end of AVL INSERTION
void AVL::displayitem()
{
display(root);
}
void AVL::display(AVLNODE *temp)
{
393
Rahul Publications
B.Sc. II YEAR III SEMESTER
if(temp==NULL)
return;
cout<<temp->data<<" ";
display(temp->left);
display(temp->right);
}
void AVL::removeitem(int x)
{
search(x);
if(loc==NULL)
{
cout<<"\nitem is not in tree :(";
}
return;
n s
if(loc->right!=NULL&&loc->left!=NULL)
remove1(loc,par,x);
c a tio
else
b l i
remove2(loc,par,x);
P u
ul
}
void AVL::remove1(AVLNODE *l,AVLNODE *p,int x)
{
a h
R
AVLNODE *ptr,*save,*suc,*psuc;
ptr=l->right;
save=l;
while(ptr->left!=NULL)
{
save=ptr;
ptr=ptr->left;
}
suc=ptr;
psuc=save;
remove2(suc,psuc,x);
if(p!=NULL)
if(l==p->left)
394
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
p->left=suc;
else
p->right=suc;
else
root=l;
suc->left=l->left;
suc->right=l->right;
return;
}
void AVL::remove2(AVLNODE *s,AVLNODE *p,int x)
{
AVLNODE *child;
if(s->left==NULL && s->right==NULL)
child=NULL;
n s
else if(s->left!=NULL)
child=s->left;
c a tio
else
b l i
child=s->right;
P u
ul
if(p!=NULL)
if(s==p->left)
a
p->left=child;h
else
R
p->right=child;
else
root=child;
}
void AVL::search(int x)
{
search1(root,x);
}
void AVL::search1(AVLNODE *temp,int x)
{
AVLNODE *ptr,*save;
int flag;
395
Rahul Publications
B.Sc. II YEAR III SEMESTER
if(temp==NULL)
{
cout<<"\nthe tree is empty";
return;
}
if(temp->data==x)
{
cout<<"\nThe item is root and is found :)";
par=NULL;
loc=temp;
par->left=NULL;
par->right=NULL;
s
return;
}
if( x < temp->data)
tio n
{
l i c a
ptr=temp->left;
save=temp;
u b
}
else
ul P
{
a h
R
ptr=temp->right;
save=temp;
}
while(ptr!=NULL)
{
if(x==ptr->data)
{
flag=1;
cout<<"\nItemfound :)";
loc=ptr;
par=save;
}
if(x<ptr->data)
396
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
ptr=ptr->left;
else
ptr=ptr->right;
}
if(flag!=1)
{
cout<<"Item is not there in tree :(";
loc=NULL;
par=NULL;
cout<<loc;
cout<<par;
}
s
}
int main()
{
tio n
AVL a;
l i c a
int x,y,c;
char ch;
u b
do
{
ul P
a h
cout<<"\n1.Insert";
R
cout<<"\n2.Display";
cout<<"\n3.Delete";
cout<<"\n4.Search";
cout<<"\n5.Exit";
cout<<"\nEnter your choice of operation on AVL Tree :";
cin>>c;
switch(c)
{
case 1:
cout<<"\nEnter an Element to be inserted into Tree :";
cin>>x;
a.insert(x);
break;
397
Rahul Publications
B.Sc. II YEAR III SEMESTER
case 2:
a.displayitem();
break;
case 3:
cout<<"\nEnter an item for Deletion :";
cin>>y;
a.removeitem(y);
break;
case 4:
cout<<"\nEnter an element to perform Search :";
cin>>c;
a.search(c);
s
break;
case 5:
exit(0);
tio n
break;
l i c a
default :
u
cout<<"\nInvalid option try again"; b
}
ul P
cout<<"\nDo u want to continue (y/n) :";
cin>>ch;
a h
}
R
while(ch=='y'||ch=='Y');<br> return 0;
}
OUTPUT:
1.Insert
2.Display
3.Delete
4.Search
5.Exit
Enter your choice of operation on AVL Tree :1
Enter an Element to be inserted into Tree :10
Do u want to continue (y/n) :y
1.Insert
398
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
2.Display
3.Delete
4.Search
5.Exit
Enter your choice of operation on AVL Tree :1
Enter an Element to be inserted into Tree :14
Do u want to continue (y/n) :y
1.Insert
2.Display
3.Delete
4.Search
5.Exit
Enter your choice of operation on AVL Tree :1
Enter an Element to be inserted into Tree :9
n s
tio
Do u want to continue (y/n) :y
1.Insert
2.Display
l i c a
3.Delete
u b
4.Search
5.Exit
ul P
h
Enter your choice of operation on AVL Tree :2
a
10 9 14
14 R
Write C++ programs for sorting a given list of elements in ascending order using the
following sorting methods.
Ans :
a) Quick sort
#include<iostream>
#include<cstdlib>
usingnamespace std;
void swap(int*a,int*b){
int temp;
temp=*a;
*a =*b;
*b = temp;
}
399
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
swap(&a[h],&a[pvt]);
P u
ul
returnPartition(a, l, h);
}
a h
intQuickSort(int a[],int l,int h){
int pindex;
if(l < h){
R
pindex=RandomPivotPartition(a, l, h);
QuickSort(a, l, pindex-1);
QuickSort(a, pindex+1, h);
}
return0;
}
int main(){
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
400
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
b l i
#include<iostream>
P u
ul
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
a h
usingnamespacestd;
R
voidmerge_sort(int, int);
voidmerge_array(int, int, int, int);
int arr_sort[MAX_SIZE];
intmain(){
int i;
cout<<"Simple C++ Merge Sort Example - Functions and Array\n";
cout<<"\nEnter "<< MAX_SIZE <<" Elements for Sorting : "<<endl;
for (i = 0; i < MAX_SIZE; i++)
cin>> arr_sort[i];
cout<<"\nYour Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout<<"\t"<< arr_sort[i];
401
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
merge_sort(0, MAX_SIZE - 1);
cout<<"\n\nSorted Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout<<"\t"<< arr_sort[i];
}
getch();
}
voidmerge_sort(int i, int j){
int m;
if (i < j) {
m = (i + j) / 2;
merge_sort(i, m);
merge_sort(m + 1, j);
n s
// Merging two arrays
merge_array(i, m, m + 1, j);
c a tio
}
b l i
}
P u
ul
voidmerge_array(int a, int b, int c, int d){
int t[50];
a
int i = a, j = c, k = 0; h
R
while (i <= b && j <= d) {
if (arr_sort[i] < arr_sort[j])
t[k++] = arr_sort[i++];
else
t[k++] = arr_sort[j++];
}
//collect remaining elements
while (i <= b)
t[k++] = arr_sort[i++];
while (j <= d)
t[k++] = arr_sort[j++];
for (i = a, j = 0; i <= d; i++, j++)
arr_sort[i] = t[j];
402
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
Output
Enter 5 Elements for Sorting
67
57
45
32
13
Your Data : 6757453213
Sorted Data :1332455767
15. Write a C++ program to find optimal ordering of matrix multiplication.
Ans :
#include<stdio.h>
#include<limits.h>
n s
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
c a tio
i
int MatrixChainMultiplication(int p[], int n)
{
int m[n][n];
u b l
int i, j, k, L, q;
ul P
for (i=1; i<n; i++)
m[i][i] = 0;
a h
//number of multiplications are 0(zero) when there is only one matrix
R
//Here L is chain length. It varies from length 2 to length n.
for (L=2; L<n; L++)
{
for (i=1; i<n-L+1; i++)
{
j = i+L-1;
m[i][j] = INT_MAX; //assigning to maximum value
for (k=i; k<=j-1; k++)
{
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of multiplications found less that number will be updated.
403
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
}
}
}
return m[1][n-1]; //returning the final answer which is M[1][n]
}
int main()
{
int n,i;
printf("Enter number of matrices\n");
scanf("%d",&n);
n++;
int arr[n];
n s
tio
printf("Enter dimensions \n");
for(i=0;i<n;i++)
{
l i c a
printf("Enter d%d :: ",i);
u b
}
scanf("%d",&arr[i]);
ul P
h
int size = sizeof(arr)/sizeof(arr[0]);
a
}
return 0; R
printf("Minimum number of multiplications is %d ", MatrixChainMultiplication(arr, size));
Output
Enter number of matrices
4
Enter dimensions
Enter d0 :: 10
Enter d1 :: 100
Enter d2 :: 20
Enter d3 :: 5
Enter d4 :: 80
Minimum number of multiplications is 19000
404
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
16. Write a C++ program that uses dynamic programming algorithm to solve the optimal
binary search tree problem
Ans :
#include <iostream>
#include <climits>
using namespace std;
// Find optimal cost to construct a binary search tree from keys
// `i` to `j`, where each key `k` occurs `freq[k]` number of times
int findOptimalCost(int freq[], int i, int j, int level)
{
// base case
if (j < i) {
return 0;
}
n s
tio
int optimalCost = INT_MAX;
l i a
// consider each key as a root and recursively find an optimal solution
c
{
u b
ul P
// recursively find the optimal cost of the left subtree
int leftOptimalCost = findOptimalCost(freq, i, k - 1, level + 1);
a h
// recursively find the optimal cost of the right subtree
int rightOptimalCost = findOptimalCost(freq, k + 1, j, level + 1);
R
// current node's cost is `freq[k]×level`
int cost = freq[k] * level + leftOptimalCost + rightOptimalCost;
// update the optimal cost
optimalCost = min (optimalCost, cost);
}
// Return minimum value
return optimalCost;
}
int main()
{
int freq[] = { 25, 10, 20 };
int n = sizeof(freq) / sizeof(freq[0]);
cout << "The optimal cost of constructing BST is "
405
Rahul Publications
B.Sc. II YEAR III SEMESTER
Ans :
#include <iostream>
#include<list>
using namespace std;
class hashclass
{
int bucket; //no of buckets you want
n s
tio
list<int>*hashtable;//container
public:
hashclass(int a)//constructor
l i c a
{
bucket=a;
u b
ul P
hashtable=new list<int>[bucket];
}
a h
void insert_element(int key)//function used to insert elements to the hashtable
{
R
//to get the hash index of key
int indexkey=hashFunction(key);
hashtable[indexkey].push_back(key);
}
void delete_element(int key)//function used to delete elements from the hashtable
{
int indexkey=hashFunction(key);
list<int>::iterator i=hashtable[indexkey].begin();
for(;i!=hashtable[indexkey].end();i++)
{
if(*i==key)
break;
406
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
if(i!=hashtable[indexkey].end())
{
hashtable[indexkey].erase(i);
}
}
int hashFunction(int a)//function used to map values to key
{
return (a%bucket);
}
void display_table()//used to display hashtable values
{
for(int i=0;i<bucket;i++)
n s
tio
{
cout<<i;
list<int>::iterator j=hashtable[i].begin();
l i c a
for(;j!=hashtable[i].end();j++)
u b
{
cout<<"---->"<<*j;
ul P
}
a h
}
}
cout<<endl;
R
void search_element(int key)//used to search element
{
int a=0;//will be 1 if element exist otherwise 0
int indexkey=hashFunction(key);
list<int>::iterator i=hashtable[indexkey].begin();
for(;i!=hashtable[indexkey].end();i++)
{
if(*i==key)
{
a=1;
break;
407
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
}
if(a==1)
{
cout<<"The element you wanted to search is present in the hashtable."<<endl;
}
else
{
cout<<"Element not present"<<endl;
}
}
~hashclass()//destructor
{
delete[]hashtable;
n s
tio
}
};
int main()
l i c a
{
u b
int bucketn,ch,element;
ul
cout<<"enter the no of buckets"<<endl; P
cin>>bucketn;
a h
while(1)
{
R
hashclass hashelement(bucketn);
408
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
hashelement.insert_element(element);
break;
case 2:cout<<"enter the element you want to search"<<endl;
cin>>element;
hashelement.search_element(element);
break;
case 3:cout<<"enter the element to be deleted"<<endl;
cin>>element;
hashelement.delete_element(element);
break;
case 4:hashelement.display_table();
break;
case 5:return 0;
default:cout<<"enter a valid value"<<endl;
n s
tio
}
}
return 0;
l i c a
}
u b
SAMPLE OUTPUT:
enter the no of buckets
ul P
4
a h
R
1.insert element to the hashtable
2.search element from the hashtable
3.delete element from the hashtable
4.display elements of the hashtable
5.exit
enter your choice
1
enter the element
13
1.insert element to the hashtable
2.search element from the hashtable
3.delete element from the hashtable
4.display elements of the hashtable
5.exit
409
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
// we are using an array to create min heap
P u
ul
void heapify(int arr[], int i)
{
a h
int smallest = i; // The node which will be heapified
R
int l = 2 * i + 1; // left child node
int r = 2 * i + 2; // right child node
// Check if left child is smaller than its parent
if (l < n && arr[l] < arr[smallest])
smallest = l;
// Check if right child is smaller than smallest
if (r < n && arr[r] < arr[smallest])
smallest = r;
// If smallest is not parent
if (smallest != i) {
swap(arr[i], arr[smallest]);
// Recursively heapify the affected sub-tree
heapify(arr, smallest);
410
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
}
// Function to build a Max-Heap from the given array
void buildHeap(int arr[])
{
// Perform level order traversal
// from last non-leaf node and heapify each node
for (int i = n; i >= 0; i--) {
heapify(arr, i);
}
}
// Driver Code
int main()
{
// Sample array
n s
int arr[] = { 1, 5, 6, 8, 9, 7, 3};
// calculating size of array
c a tio
n = sizeof(arr) / sizeof(arr[0]);
b l i
for (int i = 0; i < n; ++i)
P u
cout<< "Array representation before buildHeap is: "<<endl;
411
Rahul Publications
B.Sc. II YEAR III SEMESTER
b) Insertion
#include<iostream>
using namespace std;
/*Heapify using Bottom up approach*/
void heapify(int a[],int n,int i)
{
int parent;
parent = (i-1)/2; //for finding the parent of child
if(parent>=0) //Check until index < 0
{
if(a[parent]<a[i])
{
swap(a[parent],a[i]);
heapify(a,n,parent); //recursive heapify function
n s
}
}
c a tio
}
b l i
/*Inserting the New Element into the Heap*/
P u
ul
void insert(int a[],int &n,int val)
{
a h
/*Increase the Size of the Array by 1*/
n=n+1;
R
/*Insert the new element at the end of the Array*/
a[n-1]=val;
/*Heapify function*/
heapify(a,n,n-1);
}
/*Printing the Heap*/
void print(int a[],int n)
{
cout<<"\nThe Array Representation of Heap is\n";
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
412
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
}
/*Driver Function*/
int main()
{
/*Initial Max Heap is */
int a[100]={10,5,3,2,4};
int n = 5;
/*The Element to be insert is 15*/
int val = 15;
/*Printing the Array*/
print(a,n);
s
/*Insert Function*/
insert(a,n,val); //here we are passing the 'n' value by reference
/*Printing the Array*/
tio n
print(a,n);
l i c a
}
return 0;
u b
OUTPUT
The Array Representation of Heap is
ul P
10 5 3 2 4
a h
R
The Array Representation of Heap is //After inserting new element 15 is
15 5 10 2 4 3
c) Deletion
#include<iostream>
using namespace std;
/*Heapify the heap using top down approach*/
void heapify(int a[],int n,int i)
{
int parent = i;
//checking whether the parent index is valid in the array or not
if(i<n)
{
//formula for finding left subtree of parent
413
Rahul Publications
B.Sc. II YEAR III SEMESTER
s
//swaping the parent with largest children
swap(a[right],a[parent]);
tio n
heapify(a,n,right); //Recursively heapify the heap
}
l i c a
else
{
u b
ul P
swap(a[left],a[parent]);
heapify(a,n,right);
a h}
}
}
R
}
}
// Function to delete the root from Heap
void DeleteElement(int a[],int &n)
{
swap(a[0],a[n-1]); // swaping root and the last element
n=n-1; // Decrease size of heap by 1
heapify(a,n,0); //heapify the root node
}
/*Printing the Heap*/
void printArray(int a[],int n)
414
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
/*Driver Function*/
int main()
{
/*Initial Max Heap is */
int a[] = {10,5,3,2,4};
int n=5;
cout<<"Before Deletion"<<endl;
/*Printing the Array*/
n s
printArray(a,n);
/*Deleting the root*/
c a tio
DeleteElement(a,n);
b l i
cout<<"\nAfter Deletion"<<endl;
P u
ul
/*Printing the Array*/
printArray(a,n);
return 0;
a h
}
OUTPUT
R
Before Deletion
10 5 3 2 4
After Deletion
5432
19. Write C++ programs to perform following operations on Skip List
Ans :
a) Insertion b) Deletion
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
415
Rahul Publications
B.Sc. II YEAR III SEMESTER
#define MAX_LEVEL 6
constfloat P =0.5;
usingnamespace std;
/*
* Skip Node Declaration
*/
struct snode
{
int value;
snode**forw;
snode(int level, int&value)
{
forw=new snode *[level +1];
memset(forw, 0, sizeof(snode*)*(level +1));
n s
this->value = value;
}
c a tio
~snode()
b l i
{
P u
ul
delete[] forw;
}
};
a h
/*
R
* Skip List Declaration
*/
struct skiplist
{
snode*header;
int value;
int level;
skiplist()
{
header=new snode(MAX_LEVEL, value);
level=0;
}
416
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
~skiplist()
{
delete header;
}
void display();
bool contains(int&);
void insert_element(int&);
void delete_element(int&);
};
/*
* Main: Contains Menu
*/
int main()
{
n s
skiplist ss;
int choice, n;
c a tio
while(1)
b l i
{
P u
ul
cout<<endl<<"-----------------------"<<endl;
cout<<endl<<"Operations on Skip list"<<endl;
a h
cout<<endl<<"-----------------------"<<endl;
R
cout<<"1.Insert Element"<<endl;
cout<<"2.Delete Element"<<endl;
cout<<"3.Search Element"<<endl;
cout<<"4.Display List "<<endl;
cout<<"5.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case1:
cout<<"Enter the element to be inserted: ";
cin>>n;
ss.insert_element(n);
417
Rahul Publications
B.Sc. II YEAR III SEMESTER
if(ss.contains(n))
cout<<"Element Inserted"<<endl;
break;
case2:
cout<<"Enter the element to be deleted: ";
cin>>n;
if(!ss.contains(n))
{
cout<<"Element not found"<<endl;
break;
}
ss.delete_element(n);
if(!ss.contains(n))
cout<<"Element Deleted"<<endl;
n s
break;
case3:
c a tio
cout<<"Enter the element to be searched: ";
b l i
cin>>n;
P u
ul
if(ss.contains(n))
cout<<"Element "<<n<<" is in the list"<<endl;
else
a h
R
cout<<"Element not found"<<endl;
case4:
cout<<"The List is: ";
ss.display();
break;
case5:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return0;
418
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
/*
* Random Value Generator
*/
float frand()
{
return(float)rand()/RAND_MAX;
}
/*
* Random Level Generator
*/
int random_level()
s
{
staticbool first =true;
if(first)
tio n
{
l i c a
srand((unsigned)time(NULL));
first=false;
u b
}
ul P
int lvl =(int)(log(frand())/log(1.-P));
a h
return lvl < MAX_LEVEL ?lvl : MAX_LEVEL;
}
/*
R
* Insert Element in Skip List
*/
void skiplist::insert_element(int&value)
{
snode*x = header;
snode*update[MAX_LEVEL +1];
memset(update, 0, sizeof(snode*)*(MAX_LEVEL +1));
for(int i = level;i >=0;i--)
{
while(x->forw[i]!=NULL&& x->forw[i]->value < value)
{
419
Rahul Publications
B.Sc. II YEAR III SEMESTER
x = x->forw[i];
}
update[i]= x;
}
x = x->forw[0];
if(x ==NULL|| x->value != value)
{
int lvl = random_level();
if(lvl > level)
{
for(int i = level +1;i <= lvl;i++)
{
update[i]= header;
}
n s
level= lvl;
}
c a tio
x =newsnode(lvl, value);
b l i
for(int i =0;i <= lvl;i++)
P u
ul
{
x->forw[i]= update[i]->forw[i];
a
update[i]->forw[i]= x; h
}
}
R
}
/*
* Delete Element from Skip List
*/
void skiplist::delete_element(int&value)
{
snode*x = header;
snode*update[MAX_LEVEL +1];
memset(update, 0, sizeof(snode*)*(MAX_LEVEL +1));
for(int i = level;i >=0;i--)
{
420
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
s
break;
update[i]->forw[i]= x->forw[i];
}
tio n
delete x;
l i c a
while(level >0&& header->forw[level]==NULL)
{
u b
level--;
}
ul P
}
a h
}
/*
R
* Display Elements of Skip List
*/
void skiplist::display()
{
const snode *x = header->forw[0];
while(x !=NULL)
{
cout<< x->value;
x = x->forw[0];
if(x !=NULL)
cout<<" - ";
421
Rahul Publications
B.Sc. II YEAR III SEMESTER
}
cout<<endl;
}
/*
* Search Elemets in Skip List
*/
bool skiplist::contains(int&s_value)
{
snode*x = header;
for(int i = level;i >=0;i--)
{
while(x->forw[i]!=NULL&& x->forw[i]->value < s_value)
{
x = x->forw[i];
n s
}
}
c a tio
x = x->forw[0];
b l i
return x !=NULL&& x->value == s_value;
}
P u
OUTPUT
a h
--------------------------------- ul
R
Operations on Skip list
---------------------------------
1.Insert Element
2.Delete Element
3.Search Element
4.Display List
5.Exit
Enter your choice :1
Enter the element to be inserted: 7
Element Inserted
---------------------------------
Operations on Skip list
---------------------------------
422
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
1.Insert Element
2.Delete Element
3.Search Element
4.Display List
5.Exit
Enter your choice :1
Enter the element to be inserted: 9
Element Inserted
---------------------------------
Operations on Skip list
---------------------------------
1.Insert Element
2.Delete Element
3.Search Element
n s
4.Display List
5.Exit
c a tio
Enter your choice :4
b l i
The List is: 7 - 9
20.
P u
Write a C++ Program to Create a Graph using Adjacency Matrix Representation.
Ans :
#include <iostream>
a h ul
using namespace std;
R
// stores adjacency list items
struct adjNode {
int val, cost;
adjNode* next;
};
// structure to store edges
struct graphEdge {
int start_ver, end_ver, weight;
};
class DiaGraph{
// insert new nodes into adjacency list from given graph
adjNode* getAdjListNode(int value, int weight, adjNode* head) {
423
Rahul Publications
B.Sc. II YEAR III SEMESTER
b l i
head[i] = nullptr;
P u
ul
// construct directed graph by adding edges to it
for (unsigned i = 0; i < n; i++) {
a h
int start_ver = edges[i].start_ver;
R
int end_ver = edges[i].end_ver;
int weight = edges[i].weight;
// insert in the beginning
adjNode* newNode = getAdjListNode(end_ver, weight, head[start_ver]);
// point head pointer to new node
head[start_ver] = newNode;
}
}
// Destructor
~DiaGraph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
424
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
}
};
// print all adjacent vertices of given vertex
void display_AdjList(adjNode* ptr, int i)
{
while (ptr != nullptr) {
cout << "(" << i << ", " << ptr->val
<< ", " << ptr->cost << ") ";
ptr = ptr->next;
}
cout << endl;
}
// graph implementation
int main()
n s
{
// graph edges array.
c a tio
graphEdge edges[] = {
b l i
u
// (x, y, w) -> edge from x to y with weight w
P
ul
{0,1,2},{0,2,4},{1,4,3},{2,3,2},{3,1,4},{4,3,3}
};
int N = 6;
a h
// Number of vertices in the graph
R
// calculate number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
DiaGraph diagraph(edges, n, N);
// print adjacency list representation of graph
cout<<"Graph adjacency list "<<endl<<"(start_vertex, end_vertex, weight):"<<endl;
for (int i = 0; i < N; i++)
{
// display adjacent vertices of vertex i
display_AdjList(diagraph.head[i], i);
}
return 0;
}
425
Rahul Publications
B.Sc. II YEAR III SEMESTER
Output:
Graph adjacency list
(start_vertex, end_vertex, weight):
(0, 2, 4) (0, 1, 2)
(1, 4, 3)
(2, 3, 2)
(3, 1, 4)
(4, 3, 3)
21. Write a C++ program to implement graph traversal techniques
Ans :
a) BFS
#include<iostream>
#include<conio.h>
#include<stdlib.h>
n s
int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];
c a tio
i
int main()
{
int m;
u b l
cout <<"Enter no of vertices:";
ul P
h
cin >> n;
cin >> m;
R a
cout <<"Enter no of edges:";
426
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
while(k<n)
{
for(j=1; j<=n; j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
qu[rare++]=j;
}
v=qu[front++];
cout<<v <<" ";
k++;
visit[v]=0;
}
visited[v]=1;
n s
}
return 0;
c a tio
OUTPUT
b l i
Enter no of vertices:4
P u
ul
Enter no of edges:4
EDGES
12
a h
13
24
R
34
Enter initial vertex to traverse from:1
Visited vertices:1 2 3 4
12
b) DFS
#include<iostream>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
int main()
{
427
Rahul Publications
B.Sc. II YEAR III SEMESTER
int m;
cout <<"Enter no of vertices:";
cin >> n;
cout <<"Enter no of edges:";
cin >> m;
cout <<"\nEDGES \n";
for(k=1; k<=m; k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"Enter initial vertex to traverse from:";
s
cin >>v;
cout <<"DFS ORDER OF VISITED VERTICES:";
cout << v <<" ";
tio n
visited[v]=1;
l i c a
k=1;
while(k<n)
u b
{
for(j=n; j>=1; j--)
ul P
a h
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
R
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v << " ";
k++;
visit[v]=0;
visited[v]=1;
}
return 0;
}
428
Rahul Publications
PRACTICALS DATA STRUCTURE USING C++
OUTPUT
Enter no of vertices:4
Enter no of edges:4
EDGES
12
13
24
34
Enter initial vertex to traverse from:1
DFS ORDER OF VISITED VERTICES:1 2 4 3
22. Write a C++ program to Heap sort using tree structure.
Ans :
#include <iostream>
using namespace std;
// function to heapify the tree
n s
void heapify(int arr[], int n, int root)
{
c a tio
int largest = root; // root is the largest element
b l i
int l = 2*root + 1; // left = 2*root + 1
int r = 2*root + 2; // right = 2*root + 2
P u
ul
// If left child is larger than root
largest = l;
a h
if (l < n && arr[l] > arr[largest])
R
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != root)
{
//swap root and largest
swap(arr[root], arr[largest]);
// Recursively heapify the sub-tree
heapify(arr, n, largest);
}
}
// implementing heap sort
void heapSort(int arr[], int n)
429
Rahul Publications
B.Sc. II YEAR III SEMESTER
{
// build heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// extracting elements from heap one by one
for (int i=n-1; i>=0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// again call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/* print contents of array - utility function */
void displayArray(int arr[], int n)
n s
{
for (int i=0; i<n; ++i)
c a tio
cout << arr[i] << " ";
b l i
}
cout << "\n";
P u
// main program
int main()
a h ul
R
{
int heap_arr[] = {4,17,3,12,9,6};
int n = sizeof(heap_arr)/sizeof(heap_arr[0]);
cout<<"Input array"<<endl;
displayArray(heap_arr,n);
heapSort(heap_arr, n);
cout << "Sorted array"<<endl;
displayArray(heap_arr, n);
}
Output:
Input array
4 17 3 12 9 6
Sorted array
3 4 6 9 12 17
430
Rahul Publications
SOLVED MODEL PAPERS DATA STRUCTURES USING C++
FACULTY OF SCIENCE
B.Sc. II Year III - Semester (CBCS) Examination
Model Paper - I
DATA STRUCTURES USING C++
PAPER - III : (COMPUTER SCIENCE)
Time : 3 Hours] [Max. Marks : 80
PART - A (8 × 4 = 32 Marks)
(Short Answer Type)
Note : Answer any Eight of the following questions.
1. What is Algorithm? What are the characteristics of an algorithm ? (Unit-I, SQA-3)
2. What are the differences between Pseudocode and Algorithms. (Unit-I, SQA-6)
3. What is multiple stack. (Unit-I, SQA-14)
4.
5.
What are the differences between Iteration and recursion.
List out the basic operation of a Queue.
o n s (Unit-II, SQA-7)
(Unit-II, SQA-9)
6. List out the applications of Queues.
t i (Unit-II, SQA-12)
7.
8.
Explain ADT of Binary Tree
l i ca
Apply the bubble sort algorithm to sort the list of data: 2, 10, 6, 4, 8.
b
(Unit-III, SQA-3)
(Unit-III, SQA-6)
Pu
9. What are the pros of binary search. (Unit-III, SQA-9)
10. Minimum spanning trees. (Unit-IV, SQA-3)
11. Adjacency Matrix.
ul (Unit-IV, SQA-1)
ah
12. Min Heap (Unit-IV, SQA-6)
R PART - B (4 × 12 = 48 Marks)
(Essay Answer Type)
Note : Answer ALL the questions.
13. (a) What is a Stack? List out the standard operations of Stack ? (Unit-I, Q.No. 28)
OR
(b) Explain the process of converting infix to prefix notation. (Unit-I, Q.No. 45)
14. (a) Explain various types of recursions. (Unit-II, Q.No. 14)
OR
(b) What is mean by Queue? What are the basic operations of Queue? (Unit-II, Q.No. 19)
15. (a) Explain about various traversal techniques of binary tree. (Unit-III, Q.No. 10)
OR
(b) What is insertion sort? Explain its working with an example. (Unit-III, Q.No. 29)
16. (a) What are the various ways to represent graphs? (Unit-IV, Q.No. 2)
OR
(b) Explain Kruskal’s Algorithm with an example. (Unit-IV, Q.No. 12)
431
Rahul Publications
B.Sc. II YEAR III SEMESTER
FACULTY OF SCIENCE
B.Sc. II Year III - Semester (CBCS) Examination
Model Paper - II
DATA STRUCTURES USING C++
PAPER - III : (COMPUTER SCIENCE)
Time : 3 Hours] [Max. Marks : 80
PART - A (8 × 4 = 32 Marks)
(Short Answer Type)
Note : Answer any Eight of the following questions.
1. List out the basic characteristics of an algorithm. (Unit-I, SQA-4)
2. What are the differences between algorithm and flow chart. (Unit-I, SQA-8)
3. Lest out the applications of a stack. (Unit-I, SQA-15)
4. List out the advantages and disadvantages of recursion ? (Unit-II, SQA-2)
5. Write a c++ program to reverse a number using recursion.
n s (Unit-II, SQA-4)
tio
6. What is recursive function? (Unit-II, SQA-6)
7. What is binary tree?
il ca
(Unit-III, SQA-1)
8. Explain ADT of Binary Tree (Unit-III, SQA-3)
ub
9. Compare various sorting techniques with real world usage. (Unit-III, SQA-5)
10. What is Heap? (Unit-IV, SQA-4)
11.
12.
Representation of Graphs.
ul P
What is collision resolution technique?
(Unit-IV, SQA-9)
(Unit-IV, SQA-10)
R ah PART - B (4 × 12 = 48 Marks)
(Essay Answer Type)
Note : Answer ALL the questions.
13. (a) What is the use of function calls in stack implementation? (Unit-I, Q.No. 51)
OR
(b) Explain linked list representation for implementing Stack. (Unit-I, Q.No. 32)
14. (a) Explain the representation of Queue using Linked List. (Unit-II, Q.No. 29)
OR
(b) Discuss in detail about Doubly Linked List. Explain the basic operations of
Doubly linked list. (Unit-II, Q.No. 55)
15. (a) Compare various sorting techniques with real world usage. (Unit-III, Q.No. 34)
OR
(b) How to insert a node in binary tree? Explain with an example. (Unit-III, Q.No. 8)
16. (a) Explain about BFS algorithm with an example. (Unit-IV, Q.No. 5)
OR
(b) What is heap sort? Write the heap sort algorithm? Explain with an
example. (Unit-IV, Q.No. 28)
432
Rahul Publications
SOLVED MODEL PAPERS DATA STRUCTURES USING C++
FACULTY OF SCIENCE
B.Sc. II Year III - Semester (CBCS) Examination
Model Paper - III
DATA STRUCTURES USING C++
PAPER - III : (COMPUTER SCIENCE)
Time : 3 Hours] [Max. Marks : 80
PART - A (8 × 4 = 32 Marks)
(Short Answer Type)
Note : Answer any Eight of the following questions.
1. Draw a flow chart to calculate the average of two numbers. (Unit-I, SQA-7)
2. What is recursion ? (Unit-I, SQA-21)
3. What are the advantages of prefix and postfix expressions? (Unit-I, SQA-26)
4. What are the differences between stack and Queue. (Unit-II, SQA-13)
5. What are the advantges of a linked list.
n s (Unit-II, SQA-16)
tio
6. Why linked list is called dynamic data structure? What are the advantages of
using linked list over array. (Unit-II, SQA-20)
il ca
7. Write a C++ program for creation and traversal of a Binary Tree (Unit-III, SQA-2)
8. What is Search ?
ub
(Unit-III, SQA-4)
9. What are the applications of trees? (Unit-III, SQA-10)
10.
11.
What is graph?
Representation of Graphs.
ul P (Unit-IV, SQA-8)
(Unit-IV, SQA-9)
12.
h
What is Hashing? Define it with an example.
a
(Unit-IV, SQA-12)
R PART - B (4 × 12 = 48 Marks)
(Essay Answer Type)
Note : Answer ALL the questions.
13. (a) What are the differences between Pseudocode and Algorithms. (Unit-I, Q.No. 17)
OR
(b) Discuss in detail Stack ADT. (Unit-I, Q.No. 30)
14. (a) What is mean by Circular Queue? What is the need of circular queue? (Unit-II, Q.No. 30)
OR
(b) Write a C++ program to implement queues using arrays. (Unit-II, Q.No. 28)
15. (a) Explain the operations that can be performed on BSTs. (Unit-III, Q.No. 14)
OR
(b) Explain Binary Search with an example. (Unit-III, Q.No. 23)
16. (a) What is Closed Hashing? Explain Linear probing with example. (Unit-IV, Q.No. 20)
OR
(b) What are the different types of heaps? Explain Max heap algorithm with
an example. (Unit-IV, Q.No. 25)
433
Rahul Publications
B.Sc. II YEAR III SEMESTER
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
July - 2021
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 2 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE questions.
ANSWERS
1. Explain the attributes of ordered list with examples.
2. What is a stack? Write various applications of stack. (Unit-I, Q.No.34)
o n s (Unit-II, SQA-45)
5.
6.
What is binary tree abstract data type?
Explain hashing with an example.
a t i (Unit-III, SQA-3)
(Unit-IV, SQA-12)
7.
8.
Describe searching process using an array.
Write the comparisons of sorting techniques.
ub lic (Unit-III, SQA-4)
(Unit-III, SQA-5)
9.
10.
ul P
Define Flowchart. Discuss the different symbols in Flowchart.
Write short notes on Double-ended queue.
(Unit-I, Q.No.18)
(Unit-I, Q.No.34)
11.
12.
R ah
Write short notes on Collision Resolution strategies.
What is a Heap Abstract Data Type?
PART - B - (3 × 20 = 60 Marks)
(Unit-IV, SQA-10)
(Unit-IV, SQA-11)
15. Demonstrate and explain circular queue with examples and algorithm. (Unit-II, Q.No.30,31,32)
16. What is recursion and write an example for recursion? (Unit-II, Q.No.1)
20. What is merge sort? Explain with an example and an algorithm. (Unit-III, Q.No.31)
434
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
November / December - 2019
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 3 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE of the following questions.
ANSWERS
1. Define data structure and describe the types of data structure. (Unit-I, SQA-1, Q.No.5)
3.
s
Why linked list is called dynamic data structure? What are the advantages
n
tio
of using linked list over arrays? (Unit-II, SQA-20)
4.
5.
Describe execution of recursive calls with example.
What are the binary tree application?
l i c a (Unit-II, SQA-21)
(Unit-III, SQA-10)
7.
8.
Write a program for sequential search.
l Pu
What is heap? Explain heap construction process.
u
(Out of Syllabus)
(Unit-IV, SQA-3)
ah
PART - B - (4 × 15 = 60 Marks)
[Essay Answer Type]
(a) (i)
R
Note : Answer ALL the questions from the following.
9. What is an array and explain its advantages and disadvantages? (Out of Syllabus)
OR
(b) Write a program to implement the stack abstract data type using an array. (Unit-I, SQA-30)
10. (a) (i) What is recursion and write an example for recursion? (Unit-II, Q.No.1)
(ii) What is queue? And explain about circular queue and double ended
queue. (Unit-II, Q.No.19,30,34)
OR
(b) Write a program to create a double linked list insert, delete and search for
an element operations. (Unit-II, Q.No.55,57)
435
Rahul Publications
B.Sc. II YEAR III SEMESTER
11. (a) (i) Define the binary tree and explain its properties. Explain the binary
tree traversal techniques with example. (Unit-III, Q.No.3,10)
OR
(b) What is spanning tree and minimum spanning tree? Construct minimum
spanning tree using Kruskal’s algorithm. (Unit-IV, Q.No.7,8)
Ans :
n s
c a tio
b l i
P u
ul
Steps: Mark all the nodes. Visit the least weight edges until all the nodes are visited with out loops
a h
R
436
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
n s
c a tio
b l i
P u
a h ul
R
437
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
c a tio
b l i
P u
a h ul
R
438
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
n s
c a tio
Now the weight of the graph is
b l i
u
10+10+10+30+30+20+10+20+30+40 = 210
P
ul
12. (a) (i) Sort the given list of numbers 76, 67, 36, 55, 23, 14, 6 using
(ii) Write a program for sorting the numbers in ascending order using
R ah
bubble sort.
OR
(Unit-III, Q.No.28, Refer 12(a) Dec.-17)
(b) Explain the merge sort technique and write a program for sorting the
numbers in ascending order using merge sort. (Unit-III, Q.No.31)
439
Rahul Publications
B.Sc. II YEAR III SEMESTER
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
June / July - 2019
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 3 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE of the following questions.
ANSWERS
1. Define a Data structure in terms of the triplet (D, F, A). Give an example. (Unit-I, SQA-25)
2. What are the advantages of prefix and postfix expression? (Unit-I, SQA-26)
n s (Unit-I, Q.No.34)
tio
4. Write a recursive algorithm to find XY. (Unit-II, SQA-19)
5.
6.
What are the applications of trees?
l i c a
Write the algorithm for post order traversal on a binary tree and give an
(Out of Syllabus)
example.
b (Unit-III, SQA-2)
7.
8.
Define internal and external sorting.
l
Define a heap with an example.
u Pu (Unit-III, SQA-8)
(Unit-IV, SQA-3)
ah
PART - B - (4 × 15 = 60 Marks)
[Essay Answer Type]
9.
R
Note : Answer ALL the questions.
(a) Explain the concept of subalgorithms. Write an algorithm to compute the
following using a subalgorithm: P = n! / (n – r)!
Ans :
Start
Step 1 -> Declare function for calculating factorial
intcal_n(int n)
int temp = 1
Loop for inti = 2 and i<= n and i++
Set temp = temp * i
End
return temp
440
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
10.
s
(a) Explain Tower of Hanoi using recursion. Write the algorithm and draw the
n
tio
tree representation of recursive calls of the algorithm for 3 disks. (Unit-II, Q.No.16)
OR
l i c a
(b) Explain tire representation of Queue using a linked list. (Unit-II, Q.No.29)
11.
b
(a) Define Inorder traversal algorithm with an example. Write a C ++
u
ul
algorithm of a binary tree.P
member function to implement non-recursive inorder traversal
(Unit-III, Q.No.10,11)
a h OR
examples.
(i)
R
(b) Write Graph ADT. Explain the following operations on a graph with
Insert Vertex
(ii) Delete Vertex
(iii) Insert Edge
(iv) Delete Edge (Out of Syllabus)
12. (a) Write an algorithm for Quick sort. Explain the step-by-step procedure of
quick sort on the list 25, 57, 48, 37, 12, 92, 86, 33 (Unit-III, Q.No.32, Refer 12(b) Dec.-17)
OR
(b) Discuss Binary Search algorithm with an example. Write down the Pros
and Cons of binary search method. (Unit-III, Q.No.23)
441
Rahul Publications
B.Sc. II YEAR III SEMESTER
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
November / December - 2018
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 3 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE of the following questions.
ANSWERS
1. What is the difference between Atomic and Composite data with examples? (Unit-I, SQA-23)
o n s (Unit-I, SQA-24)
3.
4. Define recursion?
a i
Explain the use of Stack to find the factorial of a number using recursion.
t
(Unit-II, SQA-1)
(Unit-II, SQA-5)
5.
l i
Construct a binary tree using the following two traversals.
c
Inorder
Pr eorder
D
A
P
B
B
H
D
E
E
A
H ub
I
C
F
F
J
I
C
J
G
G (Unit-III, SQA-7)
6. Adjacency Matrix.
ul (Unit-IV, SQA-1)
7.
a h
What are the Pros of binary search? (Unit-III, SQA-9)
8.
R
Define minheap and maxheap with examples.
PART - B - (4 × 15 = 60 Marks)
[Essay Answer Type]
(Unit-IV, SQA-6,7)
442
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
11. (a) Write the algorithm for the construction of Expression Tree. Explain the
steps to construct an expression tree for the expression E = (a + b × c)/d. (Out of Syllabus)
OR
(b) Explain the representation of graphs using the adjacency matrix, adjacency
list and adjacency multi-list. (Unit-IV, Q.No.2)
12. (a) Write a C++ program for insertion sort. Show the steps of the insertion
algorithm for the list of data. 76, 67, 36, 55, 23, 14, 6.
(Unit-IV, Q.No.29, Refer 12(a) Dec.-17)
OR
(b) Explain the step-by-step procedure to construct a heap tree using the list
of keys. 8, 20, 9, 4, 15, 10, 7, 22, 3, 12. (Unit-IV, Q.No.28)
Ans :
8, 20, 9, 4, 15, 10, 7, 22, 3, 12
n s
tio
We can heapify this by using max heap or min heap. Here we use Max heap.
l i c a
Step 1: construct a complete binary tree using the given elements
u b
ul P
a h
R
Step 2: We ensure that the tree is a max heap.
Node 22 contains greater element in its right child node.
So, we swap node22 and node 9
443
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step 3:
Node 12 contains greater element in its right child node.
So, we swap node 12 and node 4
Step 4:
Node 10 contains greater element in its right child node.
So, we swap node 10 and node 9
n s
c a tio
b l i
P u
a h ul
Step 5:
R
Node 10 contains greater element in its left child node.
So, we swap node 10 and node 15
Step 6:
Node 4 containssmaller element in its left child node.
So, we swap node 4 and node 3
444
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
Step 7:
Node 9 contains lesser element in its left child node.
So, we swap node 9 and node 7
n s
c a tio
b l i
P u
Step 8:
a h ul
Node 20 contains greater element in its left child node.
R
So, we swap node 22 and node 20
Step 9:
Node8 contains greater element in its left child node.
So, we swap node 8 and node 22
445
Rahul Publications
B.Sc. II YEAR III SEMESTER
n s
c a tio
b l i
P u
a h ul
R
446
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
May / June - 2018
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 3 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE of the following questions.
ANSWERS
1. Define an algorithm. Write the essential characteristics of an algorithm. (Unit-I, SQA-3,4)
2. Transform the following infix expressions into their equivalent postfix expressions:
A + B × (C + D) / F + D × E and (A + B D) / (E – F) + G
n s (Unit-I, SQA-22)
tio
3. Write a short notes on applications of queues. (Unit-II, SQA-12)
4.
5.
l i c a
Explain the insertion of a node in singly linked lists with examples.
Define the terms minimum spanning tree and connected components with
(Unit-II, SQA-17)
examples.
b (Unit-IV, SQA-4)
6.
7.
l Pu
Explain the hash function with any two implementation methods.
Apply the bubble sort algorithm to sort the list of data: 2,10,6,4,8.
u
(Unit-IV, SQA-5)
(Unit-III, SQA-6)
ah
8. Explain the concepts of min-heap and max-heap with examples. (Unit-IV, SQA-6,7)
R
PART - B - (4 × 15 = 60 Marks)
[Essay Answer Type]
Note : Answer ALL the questions from the following.
9. (a) (i) Explain row-major and column-major memory representations for
2-D arrays. (Out of Syllabus)
(ii) Consider an integer array, int A[3][4] in C+h If the base address
s 1050, find the address of the element A[2]|3] with row-major
and column-major representations of the array. (Out of Syllabus)
OR
(b) Explain the stack operations with program codes and examples. (Unit-I, Q.No.28,31)
10. (a) Briefly describe about the direct recursion, indirect recursion and tree
recursion with examples. (Unit-II, Q.No.14)
OR
(b) (i) What is a queue? Give the ADT for a queue. (Unit-II, Q.No.19,21,22)
447
Rahul Publications
B.Sc. II YEAR III SEMESTER
OR
(b) Briefly describe about the graph traversal techniques. For the following
graph, give the result of DFS and BFS traversals. (Unit-III, Q.No.3,5)
Ans :
n s
c a tio
b l i
P u
a h ul
R
Step1: We start from vertex 1, DFS puts all its adjacent nodes in stack
448
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
Step 2: Next visit the element at the top of the stack, i.e 3 and go its adjacent nodes. And push them
into top of the stack.
Visited: 1 3
Stack 7 6 2
n s
c a tio
b l i
Visited: 1 3 7
P u
Stack
h
8 6 2
a ul
R
Step4: Next visit the node from the top of the stack, ie 8. And push its unvisited adjacent nodes to
the top of the stack.
Visited: 1 3 7 8
Stack 5 4 6 2
Step 5: Next visit the node from the top of the stack, ie 5. And push its unvisited adjacent nodes to
the top of the stack.
449
Rahul Publications
B.Sc. II YEAR III SEMESTER
Visited: 1 3 7 8 5 2
Stack 4 6 2
Step6: Next visit the node from the top of the stack, ie 4. And push its unvisited adjacent nodes to
the top of the stack. There are no unvisited node for 4 so remove 4 from the stack.
Visited: 1 3 7 8 5 2
n s
Stack 6 2
c a tio
l i
Step7: Next visit the node from the top of the stack, ie 6. And push its unvisited adjacent nodes to
b
the top of the stack. There are no unvisited node for 4 so remove 4 from the stack.
Visited: 1 3 7 8 5 2
P u
Stack 2
a h ul
R
Step7: Next visit the node from the top of the stack, ie 6. And push its unvisited adjacent nodes to
the top of the stack. There are no unvisited node for 4 so remove 4 from the stack.
Visited: 1 3 7 8 5 2
Stack
Now the stack is empty. So all the nodes are visited. The final graph after the DFS i s
450
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
12. (a) Write the binary search algorithm and trace the steps followed to find 88 in
the following list 8,12,24,28,32,45,48,51,56,62.
Ans :
0 1 2 3 4 5 6 7 8 9 Index of thearray
8 12 24 28 32 45 48 51 56 62
Key to find K = 88
Now compare mid element with key k > mid (88> 45).
n s
tio
8 12 24 28 32 45 48 51 56 62
Mid
l i c a
Find mid in splitted array
u b
0 1 2
48 51 56 62
3
ul P
a h
R
Mid = (0+3) / 2 = 2 mid value = 56
Split array again after the mid element. Only one element left in the array
OR
(b) Write a program code for selection sort algorithm. Show the stepwise
execution of the algorithm for the following list of data: 76, 67, 36, 55, 23,
14, 6. (Unit-IV, Q.No.26,27)
Ans :
76 67 36 55 23 14 6 Unsorted array
451
Rahul Publications
B.Sc. II YEAR III SEMESTER
76 67 36 55 23 14 6
We started here , and find the minimum element and swap it with the first element of the array.
Minimum element is 6 swap 76 with 6
6 67 36 55 23 14 76
Now we start with this and find the minimum element and swap it with the second element of the
array. Now minimum element is 14 swap with 67
6 14 36 55 23 67 76
Now we start with this and find the minimum element and swap it with the third element of the
array. Now minimum element is 23 swap with 36
n s
tio
6 14 23 55 36 67 76
l i c a
u
array. Now minimum element is 36 swap with 55
b
Now we start with this and find the minimum element and swap it with the next element of the
6 14 23 36 55 67 76
ul P
a h
R
Now we start with this and find the minimum element and swap it with the next element of the
array. There is no minimum element in the array.
So array is sorted.
Sorted array
6 14 23 36 55 67 76
452
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
FACULTY OF SCIENCE
B.sc. II Year III-Semester(CBSC) Examination
November / December - 2017
DATA STRUCTURES
Paper - III : (Computer Science)
Time : 3 Hours [Max. Marks : 80
PART - A - (5 × 4 = 20 Marks)
[Short Answer type]
Note : Answer any FIVE of the following questions.
ANSWERS
1. Write the advantages and disadvantages of arrays. (Out of Syllabus)
3. Differentiate between iteration and recursion approaches in problem solving. (Unit-II, SQA-7)
o n s (Unit-II, SQA-10)
5.
6.
Briefly describe about the properties of a binary tree.
a t i
Describe the adjacency matrix and adjacency list graph representations with
(Unit-III, SQA-1)
7.
example.
ub lic
Explain the sequential search algorithm with an example.
(Unit-IV, SQA-1,2)
(Out of Syllabus)
8.
ul P
Define a heap. Build the heap tree for the list of data.
PART - B - (4 × 15 = 60 Marks)
(Unit-IV, SQA-3)
OR
(b) (i) What is a stack? Give the ADT for a stack. (Unit-I, Q.No.28,30)
10. (a) Explain the queue operations with a program code and examples. (Unit-II, Q.No.19,22)
OR
(b) Explain the operations of insertion of a node, deletion of node and traversal
in linked list with examples. (Unit-III, Q.No.46,47,48,44)
11. (a) Define binary search tree. Construct a binary search tree and explain the
operations inserting a node, searching for a key, deleting a node with
examples. (Unit-III, Q.No.13,14)
453
Rahul Publications
B.Sc. II YEAR III SEMESTER
OR
(b) Define the terms graph, tree, spanning tree and minimum spanning tree.
Construct a minimum spanning tree (step-by-step) from the following
graph using prim’s algorithm. (Unit-IV, Q.No.1,7,10)
Ans :
Step 1: choose any vertex
A
•
Step 2: Choose shortest edge from this vertex
n s
c a tio
Step 3: choose the nearest vertex not in the solution.
b l i
P u
a h ul
R
Step 4: choose the nearest edge not in the solution, if there are multiple choices, choose the random one.
Step 5: choose the nearest edge not in the solution, if there are multiple choices, choose the random one.
454
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
Step 6: choose the nearest edge not in the solution, if there are multiple choices, choose the random one.
Finally we got the spanning tree. The weight of the spanning tree is
12+1+2+14+10 = 39
12. (a) Write a program code for insertion sort algorithm. Show the stepwise
execution of the algorithm for the following list of data: 76, 67, 36, 55,
23, 14, 6.
Ans :
n s
c a tio
b l i
P u
a h ul
R
OR
(b) Write an algorithm for quick sort. Show the stepwise execution of the
algorithm for the following list of data: 25,57,48,37,12,92,86,33. (Unit-IV, Q.No.32,33)
Ans :
Pivot
455
Rahul Publications
B.Sc. II YEAR III SEMESTER
Move the left bound(L) to the right until it reaches grater than or equal to Pivot
n s
Step left
c a tio
Move right bound to the left until it finds the lesser than values to the pivot
b l i
P u
Step left
a h ul
R
Swap 12, 57
Move the left bound to the right until it reaches greater than or equal to pivot
Step right
456
Rahul Publications
SOLVED PREVIOUS QUESTION PAPERS DATA STRUCTURE USING C++
n s
c a tio
b l i
When the right bound crosses, all the left side array is sorted.
u
Move the Pivot to the final location.
P
h ul
Apply the quick sort on the left sublist
a
R
Select the pivot (Now 12 is the Pivot)
Move the Pivot to the end.
Move the right bound to the left unit it crosses. Then swap the Pivot to the left most element.
Select the Pivot (Now 33) .as there are no elements to b sorted send the pivot the end
457
Rahul Publications
B.Sc. II YEAR III SEMESTER
Step right
Move the right bound to the left until it crosses. Now all the elements of right are grater than pivot.
Move the pivot to the final location. 92 is already in final location.
n s
tio
Apply the quick sort on left sublist.
l i c a
Select the pivot 48 move the pivot to the last of the sublist
u b
ul P
Partition the subarray. Move the r and l bounds until they cross .when the right bound crosses to the
h
left all the elements of right list are greater than the pivot. Move the pivot to the last.
a
R
Call quicksort on the right sublist. Select pivot (86).
458
Rahul Publications