1. Syllabus for B.Tech. I Year II semester
Code:121CS01 DATA STRUCTURES AND C++
UNIT – I
Introduction to data structures: Abstract data type(ADT), Stacks and Queues circular queues and
their implementation with arrays. Stack applications: infix to post fix conversion, postfix
expression evaluation. Applications of queues.
UNIT – II
Singly linked lists, doubly linked lists, circular list and their operations, representing stacks and
queues with linked lists.
UNIT – III
Trees- Binary tress, terminology, representation, traversals
Graphs- terminology, representation, graph traversals (dfs & bfs).
UNIT - IV
Searching - Linear and binary search methods.
Sorting - Bubble sort, selection sort, Insertion sort, Quick sort, merge sort.
UNIT – V
Introduction to c++ programming-object oriented programming concepts, Structured Vs OOP.
Classes and objects-class definition, Objects, class scope and accessing members, Constructors-
default constructor, parameterized constructor, constructor initialization list, copy constructor.
Destructors.
UNIT – VI
Static class members, this pointer, friend functions, Dynamic memory management with operators
new and delete.Overloading-function overloading, Operator overloading, restrictions on
operator overloading, overloading unary and binary operators,templates, inheritance.
2. • Code: 121CS71 DATASTRUCTURES AND C++ LAB
(Common to all Branches)
1.Write a C program that implement stack and its operations using arrays
2. Write a C program that implement Queue and its operations using arrays.
3. Write a C program that uses Stack operations to perform the following
i) Converting infix expression into postfix expression
ii) Evaluating the postfix expression
4. Write a C program that uses functions to perform the following operations on singly
linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal
5. Write a C program that uses functions to perform the following operations on doubly
linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways
6 Write a C program that uses functions to perform the following:
i) Creating a Binary Tree of integers
ii) Traversing the above binary tree in preorder, in order and post order.
7. Write C programs that use both recursive and non recursive functions to perform the
following searching operations for a Key value in a given list of integers :
i) Linear search ii) Binary search
8. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
i) Bubble sort ii) Quick sort
9. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
i)Insertion sort ii) Merge sort iii) Selection Sort
10. Write a C++ program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a,b,c and use the quadratic formula. If the descremainant b2-4ac is negative,
display a message stating that there are no real solutions.
11. A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and
Subsequent terms are found by adding the preceding two terms in the sequence. Write a C++
program to generate the first n terms of the sequence.
12. Write a C++ program that checks whether a given string is palindrome or not.
3. UNIT-I
Topics to be covered
1.Introduction to data structures.
2. Abstract data type (ADT)
3. Stacks and queues
4. Circular queues and their implementation with arrays.
5. Stack applications:
5.1. infix to post fix conversion
5.2. postfix expression evaluation.
6. Applications of queues
4. Introduction to data structures
Data- it is a collection of items or values
Type- it is a collection of values.
ex- integer- 0 to 9
boolean- true or false
Data type- it is a data of type and together with the
set of operations used to apply on the type.
ex- integer is a member of type integer and its
operations are addition, subtraction etc…
5. 1.Introduction to data
structures.
Definition:- A data structure is an arrangement of data in a
computers memory or even on disk storage. It has a different
way of storing and organizing (accessing) data in a computer.
Objective of data structure:- manipulation of real-life data
requires the following essential tasks-
1.storage representation of user data
2. Retrieval of stored data
3. transformation of user data
6. • Mathematical definition of data
structure is D=(d,f,a)
where
D= data structure
d= a set of variables (data objects).
f= a set of functions
a= set of rules to implement the
functions.
7. 2. Abstract data type
(ADT)
Data structure is implemented around the concept of
an abstract data type that defines the data together
with the operations.
ADT contains
- data
- operations
- no implementation details.
ADT is also called as user defined data type.
Only tells about what are the data values required and
what operations performed on those objects.
8. Overview of data structures
Several data structures are available in the
computer science and used based on their
applications.
Data structures are classified into different types.
Data structure
Linear ds
Non Linear
ds
Array
s
Linked list stack queue
s
Tree
s
Graph
s
9. 1.Linear data structure-
all the elements are stored in sequential
order or linear order means that all the
elements are adjacent to each other. Each
element has exactly two neighbors.
Predecessor and successor.
• the first element does not have predecessor
• The last element does not have successor.
2. Non linear data structure- no such sequence
in elements, if one element is connected to a
more than two adjacent element then it is a
non linear data structure.
10. Applications of data
structures
Implementing data bases of different
organizations (ds used is B-Trees)
Implement compilers for different
languages (ds used is hash tables).
Used in every program and software
system.
11. 3. Stacks and queues
Definition - A stack is an ordered collection of
homogeneous data elements, where the insertion and
deletion takes place at one end, known as TOP.
The stack is also called LAST IN FIRST OUT(LIFO)
It means: the element which is inserted last must be
deleted first
Example
1. No of plates in cafeteria
2. stack of coins
12. Stack maintains a pointer called top, which keeps trackStack maintains a pointer called top, which keeps track
of the top most element in the stack.of the top most element in the stack.
Any insertions or deletions should be based upon theAny insertions or deletions should be based upon the
value of top.value of top.
It works on the basis of LIFO (Last in First out).It works on the basis of LIFO (Last in First out).
According to the definition, new elements are insertedAccording to the definition, new elements are inserted
from top and the elements are deleted from same endfrom top and the elements are deleted from same end
i.e again top.i.e again top.
This suggests that the element inserted most recentlyThis suggests that the element inserted most recently
can only be deleted.can only be deleted.
In the stack, the elements are removed in the reverseIn the stack, the elements are removed in the reverse
order of that in which they were added to the stack i.eorder of that in which they were added to the stack i.e
last element inserted is to be deleted first.last element inserted is to be deleted first.
So it is called last in first out.So it is called last in first out.
Stack has structured with two operationsStack has structured with two operations
1.1. push- insertion adding elements on to a stackpush- insertion adding elements on to a stack
2.2. Pop- deletion removing element from the stackPop- deletion removing element from the stack
13. Basic operations:Basic operations:
The basic operations are insertion, deletionThe basic operations are insertion, deletion
,display.,display.
In stacks, special terms are given for insertIn stacks, special terms are given for insert
and delete. i.e push for insert and pop is forand delete. i.e push for insert and pop is for
delete.delete.
Push: inserting or adding element into thePush: inserting or adding element into the
stack is called push.stack is called push.
Pop: deleting or removing element from thePop: deleting or removing element from the
stack is called pop.stack is called pop.
14. Elements are inserted in the order as A,B,C,D,EElements are inserted in the order as A,B,C,D,E
It represents the stack of 5 elements.It represents the stack of 5 elements.
The top most element in the stack is EThe top most element in the stack is E
If we want to delete element E has to be deleted firstIf we want to delete element E has to be deleted first
17. ADT For Stack
ADT for stack
struct stack
{
int stack[5],top;
}
void push();
void pop();
void display();
18. Implementing stack usingImplementing stack using
arraysarrays
Algorithm for inserting element into the stack:Algorithm for inserting element into the stack:
Algorithm push()Algorithm push()
1. if top=(SIZE-1)1. if top=(SIZE-1)
then write (‘stack overflow’)then write (‘stack overflow’)
elseelse
2. read item or data2. read item or data
3. top3. top top+1←top+1←
4. stack[top] item←4. stack[top] item←
5. stop5. stop
19. Explanation:Explanation:
The stack is of size max. This procedure inserts an elementThe stack is of size max. This procedure inserts an element
item on to the top of a stack which is represented by anitem on to the top of a stack which is represented by an
array stack.array stack.
The first step of this algorithm checks for an overflowThe first step of this algorithm checks for an overflow
condition.condition.
Overflow means inserting element into a stack which isOverflow means inserting element into a stack which is
full.full.
If the top value reaches to maximum size of the stack thenIf the top value reaches to maximum size of the stack then
elements cannot be inserted into the stack i.e. stack is full.elements cannot be inserted into the stack i.e. stack is full.
Otherwise top is incremented by one and element isOtherwise top is incremented by one and element is
inserted into the stack.inserted into the stack.
20. Algorithm to delete elements from the stack:Algorithm to delete elements from the stack:
Algorithm pop()Algorithm pop()
1. if top=-11. if top=-1
then write (‘stack underflow’)then write (‘stack underflow’)
elseelse
2. item2. item ← stack[top]← stack[top]
3. top ← top-13. top ← top-1
21. Explanation:Explanation:
This procedure deletes an element from the stack.This procedure deletes an element from the stack.
The first step of this algorithm checks forThe first step of this algorithm checks for
underflow condition.underflow condition.
If the top value is -1 then stack is empty.If the top value is -1 then stack is empty.
Empty stack is known as underflow.Empty stack is known as underflow.
Takeout the element from the location where, theTakeout the element from the location where, the
top is pointing and then decrement top by one.top is pointing and then decrement top by one.
22. Display of stack:Display of stack:
Printing the contents of stack after push and popPrinting the contents of stack after push and pop
operations.operations.
Algorithm print()Algorithm print()
1. if top=-11. if top=-1
then write (‘stack empty’)then write (‘stack empty’)
2. Repeat for i2. Repeat for i ← top to 0← top to 0
print(stack[i])print(stack[i])
3. stop3. stop
23. A queue is a linear data structure in which insertion take place from oneA queue is a linear data structure in which insertion take place from one
end calledend called rear endrear end and deletions take place from other end calledand deletions take place from other end called frontfront
endend i.e insertion and deletion take place from different ends.i.e insertion and deletion take place from different ends.
The principle used to in queue isThe principle used to in queue is FIFO.(First In First Out)FIFO.(First In First Out)
FIFOFIFO- the element which is inserted First must be deleted First.- the element which is inserted First must be deleted First.
In a queue there are two variables one is theIn a queue there are two variables one is the rearrear and other one isand other one is frontfront..
the element must be alwaysthe element must be always added at rearadded at rear end andend and removed from theremoved from the
frontfront..
Basic operations on queue:Basic operations on queue:
The operations that can be performed on queue areThe operations that can be performed on queue are
Insertion EnqueueInsertion Enqueue
Deletion DequeueDeletion Dequeue
DisplayDisplay
QueuesQueues
Front rear
28. FrontRear
Front
Rear
Front
Rear
•A queue is like a line of people waiting forA queue is like a line of people waiting for
• a bank teller. The queue has aa bank teller. The queue has a frontfront and aand a rearrear..
New people must enter the queue at the rear.New people must enter the queue at the rear.
When an item is taken from the queue, it always comes from the front.When an item is taken from the queue, it always comes from the front.
29. • Different types of queues
1. Linear queue or queue
2. Circular queue
3. Doubly ended queue( dequeue)
4. Priority queue
30. This type of data structure is used in timeThis type of data structure is used in time
sharing systems where many user jobs will besharing systems where many user jobs will be
waiting in the system queue for processing.waiting in the system queue for processing.
These jobs may request the services of CPU,These jobs may request the services of CPU,
main memory or external devices such asmain memory or external devices such as
printer.printer.
31. Working of a linear queue:-
i) Initially front=rear= -1. It indicates queue is empty.
0 1 2 3 4
front=rear=-1
0 1 2 3 4
ii) Add 10
10
front rear
0 2 3 4
iii) Add 20
front rear
1
10 20
0 2 3 4
iv) Add 30
front rear
1
10 20 30
0 2 3 4
v) Add 40
front rear
1
10 20 30 40
33. 0
front rear
1
40 50
x) delete (30 is removed)
2 3 4 0
front rear
1
50
xi) delete (40 is
removed)
2 3 4
0
front=rear=-1
1
ix) delete (underflow)
2 3 40
front=rear=-1
1
xii) delete (50 is removed)
2 3 4
34. Implementation of queue usingImplementation of queue using
arrayarray
Algorithm insert( )Algorithm insert( )
1.1. If rearIf rear ≥≥ size-1size-1
then write (‘overflow’)then write (‘overflow’)
2.2. Read itemRead item
3.3. rearrear←← rear + 1rear + 1
4.4. queue[rear]queue[rear]←← itemitem
5.5. If(front==-1)If(front==-1)
6.6. front++;front++;
7.7. stopstop
Explanation:Explanation:
This procedure adds an element item to theThis procedure adds an element item to the
queue.queue.
First it checks for an overflow condition.First it checks for an overflow condition.
If the rear value reaches or exceeds size of thIf the rear value reaches or exceeds size of th
queuequeue
then elements cannot be inserted into the queuethen elements cannot be inserted into the queue
ie. Overflow.ie. Overflow.
Whenever element is inserted into the queue,Whenever element is inserted into the queue,
rear is increment by onerear is increment by one
and place the element in the locationand place the element in the location
where rear is pointing.where rear is pointing.
35. Algorithm to delete element from the queueAlgorithm to delete element from the queue
Algorithm delete()Algorithm delete()
1.1. If (front= = -1)or (front> rear)If (front= = -1)or (front> rear)
then write (‘queue underflow’)then write (‘queue underflow’)
itemitem ←← queue [front]queue [front]
2. front2. front ←← front + 1front + 1
Explanation:Explanation:
This procedure deletes an element from the queue.This procedure deletes an element from the queue.
The first step of this algorithm checks for underflow condition.The first step of this algorithm checks for underflow condition.
If the front value is -1or greater than rear then queue is empty.If the front value is -1or greater than rear then queue is empty.
Take out the element from the location where, the front is pointing andTake out the element from the location where, the front is pointing and
store it in the variable, then increment front by one.store it in the variable, then increment front by one.
36. Algorithm to display elements in a queueAlgorithm to display elements in a queue
1.1. if((front==-1)||(front>rear))if((front==-1)||(front>rear))
1.1 print statck is Underflow1.1 print statck is Underflow
2. Else2. Else
2.1 repeat for i->front to rear2.1 repeat for i->front to rear
2.2. print queue[i];2.2. print queue[i];
Drawback in queue
In a queue when the rear pointer reaches to the end of the queue,
insertion would be denied even if room is available at the front
one way to remove this is using the circular queue
37. Program: implementation of queue using array
# include <stdio.h>
# define size 4
void insertion();
void deletion();
void display();
int front=-1,rear=-1,item,choice,queue[size];
void main()
{clrscr();
while(1)
{
printf("n*** MENU ***n 1. INSERTIONn 2. DELETIONn
3.TRAVERSEn 4. EXITn");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:insertion();
break;
case 2:deletion();
break;
case 3:display();
break;
case 4:exit();
38. void insertion()
{
if(rear>=size-1)
printf("*** queue is full ***n");
else
{
printf("enter item into queue:");
scanf("%d",&item);
rear++;
queue[rear]=item;
if(front==-1)
front++;
} }
void deletion()
{
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
item=queue[front];
front++;
printf("the deleted item from queue is
%dn",item);
}
}
void display(){
int i;
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
printf("n elements in queue:- ");
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
}}
41. • How to test whether circular queue is empty or full?
• The circular q is controlled by the MOD operation.
• Circular queue is empty
when front =-1
rear=-1
Circular queue is full
front = (rear+1)% SIZE
42. Implementation of circular queue using
array
• Algorithm for insertion
1.if((front == 0 && rear == SIZE-1) || (front == (rear+1)%size)
2.printf("Queue Overflow n");
return;
3.if (front == -1) /*If queue is empty */
3.1 front = 0;
3.2 rear = 0;
4.else
5.if(rear == SIZE-1)/*rear is at last position of queue */
6.rear = 0;
7. else
8.rear = rear+1;
9.Read item
10.cq[rear] = item ;
11.end
43. • Algorithm for deletion
• 1.if (front == -1)
2.printf("Queue Underflown")
return
3.if(front == rear) /* queue has only one element */
3.1front = -1;
3.2rear=-1;
4.else
5.if(front == SIZE-1)
• front = 0;
6.else
7.front = front+1;
8.Stop
44. int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and front=
%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
45. int del()
{
if (front == -1)
{
printf("Queue Underflown");
return ;
}
printf("Element deleted from queue is :
%dn",cq[front]);
if(front == rear) /* queue has only one
element */
{
front = -1;
rear=-1;
}
else
if(front == SIZE-1)
front = 0;
else
front = front+1;
printf("front=%d,rear=
%dn",front,rear);
return;
}/*End of del() */
Deletion
46. display() int display(){
int front_pos = front,rear_pos = rear;
if(front == -1){
printf("Queue is emptyn");
Return;}
printf("Queue elements :n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}
else{
while(front_pos <= SIZE-1){
printf("%d ",cq[front_pos]);
front_pos++;}
front_pos = 0;
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}}/*End of else */
printf("n");
return;
}/*End of display() */
47. Applications of queues
There are several applications of queues in computer science.
1. Implement various aspects of operating systems.
2. CPU scheduling in Multiprogramming environment- single CPU has to
serve more than one program simultaneously.
3. Round Robin CPU scheduling algorithm.
4. In operating System maintains a queue of processes that are ready
to process or that are waiting for particular event to occur.
5. Computer system maintains a buffer and is implemented as a queue.
6. Printer
7. Call waiting when you are attending other call
8. a file server in a computer network handles file access request from
many clients throughout the network. Servers have a limited capacity
to service request from clients. when that capacity is exceeded,
client requests wait in queues
9. This type of data structure is used in time sharing systems where many9. This type of data structure is used in time sharing systems where many
user jobs will be waiting in the system queue for processing. Theseuser jobs will be waiting in the system queue for processing. These
jobs may request the services of CPU, main memory or externaljobs may request the services of CPU, main memory or external
devices such as printer.devices such as printer.
48. Circular queue using array
# include<stdio.h>
#include<stdlib.h>
# define SIZE 4
int insert();
int del();
int display();
int cq[SIZE];
int front = -1;
int rear = -1;
main(){
while(1){
printf("1.Insertn");
printf("2.Deleten");
printf("3.Displayn");
printf("4.Quitn");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
insert();
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choicen");
}/*End of switch*/
}/*End of while */
}/*End of main()*/
49. int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and front=
%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
51. Applications of stacksApplications of stacks
Parenthesis matching.Parenthesis matching.
Evaluation of postfix expressions.Evaluation of postfix expressions.
Infix to prefix conversions.Infix to prefix conversions.
Infix to postfix conversions.Infix to postfix conversions.
Recursion.Recursion.
Quick sort.Quick sort.
52. 1.Parenthesis matching1.Parenthesis matching
The objective of this function is to check theThe objective of this function is to check the
matching of parenthesis in an expressionmatching of parenthesis in an expression
i.ei.e
In an expression the no of left parenthesis mustIn an expression the no of left parenthesis must
be equal to no: of right parenthesis.be equal to no: of right parenthesis.
Ex:Ex: ((A+B)*C)((A+B)*C)
This is a valid expression because in this no ofThis is a valid expression because in this no of
left parenthesis (2) = no: of right parenthesis (2).left parenthesis (2) = no: of right parenthesis (2).
53. Conversion of expressionsConversion of expressions
Arithmetic expressions can be represented in three ways:Arithmetic expressions can be represented in three ways:
Infix notationInfix notation
Prefix notationPrefix notation
Postfix notationPostfix notation
1. Infix notation- In which operator should be placed in between the two operands.
Example- A+B C-D E*F G/H.
2. Prefix notation (polish notation)-
• Operator preceded by the operand is called prefix notation
Examples
+AB -CD *EF GH.
3. Postfix notation(reverse polish notation or suffix notation)-
• Operator should be placed after operands.
AB+ CD- EF* GH
54. Notations – Conversions
Consider the infix expression: 2 + 3 * (5 – 7) / 9
Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))
Transfer the operators to the beginning of parentheses
(+ 2 (/ (* 3 (– 5 7)) 9))
Remove the parentheses: + 2 / * 3 – 5 7 9
This is the equivalent prefix expression.
Transfer the operators to the end of parentheses
(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 / +
This is the equivalent postfix expression.
56. Infix to post fix(RPN) Conversion
Algorithm to convert infix expression to RPN:
1. Declare a stack.
2. Repeat the following steps until the end of the infix expression is
reached.
1. Get input token (constant, variable, arithmetic operator, left
parenthesis, right parenthesis) in the infix expression.
2. If the token is
1. A left parenthesis: Push it onto the stack.
2. A right parenthesis:
1. Pop and display stack elements until a left parenthesis is on the
top of the stack.
2. Pop the left parenthesis also, but do not display it.
3. An operator:
1. While the stack is nonempty and token has lower or equal
priority than stack top element, pop and display.
2. Push token onto the stack.
4. An operand: Display it.
3. When the end of the infix expression is reached, pop and display stack
items until the stack is empty.
57. Note
• 1. the lower precedence operator
never placed on top of the higher
precedence.
59. Infix expression- (A+B)^C-(D*E)/F
Infix Stack Post fix
( ( Empty
A ( A
+ (+ A
B (+ AB
) Empty AB+
^ ^ AB+
C ^ AB+C
- - AB+C^
( -( AB+C^
D -( AB+C^D
* -(* AB+C^D
E -(* AB+C^DE
) - AB+C^DE*
/ -/ AB+C^DE*
F -/ AB+C^DE*F
Empty AB+C^DE*F/-
60. Postfix (reverse polish notation)
expression evaluation
• Algorithm
1.Scan expression from left to right and repeat steps 2 and 3 for each
element of expression.
2. If an operand is encountered, put it on stack.
3.If an operator op1 is encountered then
3.1 remove the top two elements of stack, where A is the top and B is
the next top element.
3.2 evaluate B op1 A
3.3 push the result back on to the stack.
4. set the top value on stack.
5. stop
When you think of a computer science queue, you can imagine a line of people waiting for a teller in a bank. The line has a front (the next person to be served) and a rear (the last person to arrive.