C++ Lab Manual - Datastructure-1
C++ Lab Manual - Datastructure-1
DEPARTMENT OF SOFTWARE
ENGINEERING
1
Data Structures through C++
INDEX
S.No Content Page No:
Programme Outcomes
Course Structure, Objectives & Outcomes
Experiments Learning Outcomes
1 Write a C++ program that uses functions to perform the following: 12
a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
2 Write a template based C++ program that uses functions to perform the 35
following:
a) Create a doubly linked list of elements.
b) Delete a given element from the above doubly linked list.
c) Display the contents of the above list after deletion.
3 Write a C++ program that uses stack operations to convert a given infix 53
expression into its postfix equivalent, Implement the stack using an array.
4 Write a C++ program to implement a double ended queue ADT using an array, 57
using a doubly linked list.
5 Write a C++ program that uses functions to perform the following: 67
a) Create a binary search tree of characters.
b) Traverse the above Binary search tree recursively in preorder, in order and
post order
6 Write a C++ program that uses function templates to perform the following: 87
a) Search for a key element in a list of elements using linear search.
b) Search for a key element in a list of sorted elements using binary search.
7 Write a C++ program that implements Insertion sort algorithm to arrange a list 90
of integers in ascending order.
8 Write a template based C++ program that implements selection sort algorithm 92
to arrange a list of elements in descending order.
9 Write a template based C++ program that implements Quick sort algorithm to 94
arrange a list of elements in ascending order.
10 Write a C++ program that implements Heap sort algorithm for sorting a list of 97
integers in ascending order.
11 Write a C++ program that implements Merge sort algorithm for sorting a list of 100
integers in ascending order
12 Write a C++ program to implement all the functions of a dictionary (ADT) 103
using hashing.
2
Data Structures through C++
13 Write a C++ program that implements Radix sort algorithm for sorting a list of 107
integers in ascending order.
14 Write a C++ program that uses functions to perform the following: 109
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in inorder.
15 Write a C++ program that uses functions to perform the following: 114
a) Create a binary search tree of integers.
b) Search for an integer key in the above binary search tree non recursively.
c) Search for an integer key in the above binary search tree recursively.
SAMPLE VIVA QUESTIONS
PEO-I solving civil engineering problems in different circumstances PEO-II Pursue higher education and
research for professional development.
PSO1. UNDERSTANDING: Graduates will have an ability to describe, analyze, and solve problems using
mathematics and systematic problem-solving techniques.
PSO2. ANALYTICAL SKILLS: Graduates will have an ability to design a system, component, or process
to meet desired needs within realistic constraints such as economic, environmental, social, political, ethical,
health and safety, manufacturability, and sustainability.
PSO3. BROADNESS: Graduates will have a broad education necessary to understand the impact of
engineering solutions in a global, economic, and societal context.
3
Data Structures through C++
4
Data Structures through C++
i) Recognition of the need for, and an ability to engage in continuing professional development and
life-long learning
Graduates should show that they appreciate the need for further education and self improvement, understand
the value of professional licensure the necessity of continuing professional developments, and the value of
membership in appropriate professional organizations.
k) An ability to use the techniques, skills, and modern engineering tools necessary for engineering
practice
Graduates should have ability to use practical methods readily and effectively in the performance of
engineering analysis and design. Graduates should be able to select and use modern engineering tools used
by practicing engineers, including computer software such as computer aided drawing (CAD)
l) An ability to apply design and development principles in the construction of software and hardware
systems of varying complexity
Civil Graduates should have ability to design and develop principles involved in construction of different
structures like buildings, shopping complexes, roads, water structures and to analyse the stability of
structures using different softwares like stadpro. Studs etc.
5
Data Structures through C++
COURSE STRUCTURE
Environmental engineering lab will have a continuous evaluation during 7 th semester for 25 sessional marks
and 50 end semester examination marks.
Out of the 25 marks for internal evaluation, day-to-day work in the laboratory shall be evaluated for 15
marks and internal practical examination shall be evaluated for 10 marks conducted by the laboratory
teacher concerned.
The end semester examination shall be conducted with an external examiner and internal examiner. The
external examiner shall be appointed by the principal / Chief Controller of examinations
COURSE OBJECTIVE
The objective of this laboratory is to determine the qualities of water and waste water characteristics. The
experiments include the determination of pH, turbidity, conductivity, and impurities in water and BOD, DO
and COD of waste water.
The highlight of this laboratory is the spectrophotometer, muffle furnace, BOD incubator, COD Digestor
etc. This laboratory course will help the students to understand the theoretical concepts learned in the course
Environmental Engineering.
COURSE OUTCOME
1. Quantify the pollutant concentration in water, wastewater
2. Recommend the degree of treatment required for the water and wastewater
HODs and faculty members are directed to submit the soft copies of the course files in the director’s
office/L.M.S at the earliest, other wise it will be treated as not submitted
6
Data Structures through C++
7
Data Structures through C++
8
Data Structures through C++
ptr=header;
while(ptr->next->next!=NULL)
{
ptr->=Ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp);
end else
}
Algorithm:delete at anyposition()
{
if (header->next==NULL)
then
display list is empty /*deletion is not possible*/
end if
ptr=header;
count=0;
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
if(count<pos-1)
{
Display position is out of range
}
ptr=header;
count=0;
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=temp->next;
free(temp)
}
Traversing a List:
Algorithm:Traverse()
{
ptr=header;
if(ptr ->next==NULL)
then
display list is empty
end if
else
9
Data Structures through C++
Source Code:
/*
* C++ Program to Implement Singly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *next;
}*start;
/*
* Class Declaration
*/
class single_llist
{
public:
node* create_node(int);
void insert_begin();
void insert_pos();
void insert_last();
void delete_pos();
void sort();
void search();
void update();
void reverse();
void display();
single_llist()
{
start = NULL;
}
};
10
Data Structures through C++
/*
* Main :contains menu
*/
main()
{
int choice, nodes, element, position, i;
single_llist sl;
start = NULL;
while (1)
{
cout<<endl<<" "<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<" "<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl;
cout<<"3.Insert node at position"<<endl;
cout<<"4.Sort Link List"<<endl;
cout<<"5.Delete a Particular Node"<<endl;
cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl;
cout<<"8.Display Linked List"<<endl;
cout<<"9.Reverse Linked List "<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break;
case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last();
cout<<endl;
break;
case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break;
case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
11
Data Structures through C++
cout<<endl;
break;
case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break;
case 6:
cout<<"Update Node Value:"<<endl;
sl.update();
cout<<endl;
break;
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search();
cout<<endl;
break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display();
cout<<endl;
break;
case 9:
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl;
break;
case 10:
cout<<"Exiting..."<<endl;
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
/*
* Creating Node
*/
node *single_llist::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
12
Data Structures through C++
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
/*
* Inserting element in beginning
*/
void single_llist::insert_begin()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
p = start;
start = temp;
start->next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}
/*
* Inserting Node at last
*/
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
13
Data Structures through C++
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
}
/*
* Insertion of node at a given position
*/
void single_llist::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if (pos > 1 && pos <= counter)
{
s = start;
for (i = 1; i < pos; i++)
{
14
Data Structures through C++
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
}
}
/*
* Sorting Link List
*/
void single_llist::sort()
{
struct node *ptr, *s;
int value;
if (start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}
ptr = start;
while (ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->info > s->info)
{
value = ptr->info;
ptr->info = s->info;
s->info = value;
}
}
ptr = ptr->next;
}
}
/*
* Delete element at a given position
*/
void single_llist::delete_pos()
{
int pos, i, counter = 0;
15
Data Structures through C++
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
/*
* Update a given Node
*/
void single_llist::update()
{
int value, pos, i;
if (start == NULL)
16
Data Structures through C++
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start->info = value;
}
else
{
for (i = 0;i < pos - 1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return;
}
s = s->next;
}
s->info = value;
}
cout<<"Node Updated"<<endl;
}
/*
* Searching an element
*/
void single_llist::search()
{
int value, pos = 0;
bool flag = false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value;
struct node *s;
s = start;
17
Data Structures through C++
while (s != NULL)
{
pos++;
if (s->info == value)
{
flag = true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
}
s = s->next;
}
if (!flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
}
/*
* Reverse Link List
*/
void single_llist::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{
return;
}
ptr1 = start;
ptr2 = ptr1->next;
ptr3 = ptr2->next;
ptr1->next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)
{
ptr1 = ptr2;
ptr2 = ptr3;
ptr3 = ptr3->next;
ptr2->next = ptr1;
}
start = ptr2;
}
/*
* Display Elements of a link list
18
Data Structures through C++
*/
void single_llist::display()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
Output:
19
Data Structures through C++
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 5
Delete a particular node:
List is empty
20
Data Structures through C++
21
Data Structures through C++
22
Data Structures through C++
10.Exit
Enter your choice : 2
Inserting node at last:
Enter the value to be inserted: 150
Element Inserted at last
23
Data Structures through C++
24
Data Structures through C++
25
Data Structures through C++
26
Data Structures through C++
27
Data Structures through C++
Viva Questions:
1. List the differences between the linked array and linked list.
2. What is meant by single linked list.
3. What type of memory allocation is referred for Linked lists?
4. name the types of Linked Lists?
5. Mention what are the applications of Linked Lists?
6. List the disadvantages of single linked list.
28
Data Structures through C++
2. Write a template based C++ program that uses functions to perform the following:
a) Create a doubly linked list of elements.
b) Delete a given element from the above doubly linked list.
c) Display the contents of the above list after deletion.
29
Data Structures through C++
if (new1== NULL)
then
display memory is full (insertion is not possible)
exit
else
read ele,pos
ptr=header
count=0
while(ptr->next!=NULL)
{
ptr=ptr->next;
count ++;
}
if(count<pos-1)
then
display position is not of range
end
ptr=header
count=0
while(count<pos-1)
then
ptr=ptr->next
count++
end
new1->data=ele;
new1->next=ptr->next;
new1->prev=ptr;
ptr->next->prev=new1;
ptr->next=new1
end else
}
Deleting a node from the DLL:
Algorithm: delete at front()
{
if (header->next==NULL)
then
display list is empty
end if
else
temp=header->next;
header->next=header->next->next;
temp->next->prev=header;
free(temp);
end if
}
Algorithm: Delete at end()
{
30
Data Structures through C++
if(header->next==NULL)
then
display list is empty
end if
else
ptr=header;
while(ptr->next->next!=NULL)
{
ptr->=Ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp);
end else
}
Algorithm:delete at anyposition()
{
if (header->next==NULL)
then
display list is empty /*deletion is not possible*/
end if
ptr=header;
count=0;
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
if(count<pos-1)
{
Display position is out of range
}
ptr=header;
count=0;
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=temp->next;
temp->next->prev=Ptr;
free(temp)
}
Traversing a List:
Algorithm:Traverse()
31
Data Structures through C++
{
ptr=header;
if(ptr ->next==NULL)
then
display list is empty
end if
else
while(ptr -> next!=NULL)
{
display ptr-> data
ptr=ptr -> next /* move to next node */
}
end if
}
Source Code:
/*
* C++ Program to Implement Doubly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
/*
* Node Declaration
*/
using namespace std;
struct node
{
int info;
struct node *next;
struct node *prev;
}*start;
/*
Class Declaration
*/
class double_llist
{
public:
void create_list(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element(int value);
void search_element(int value);
void display_dlist();
void count();
32
Data Structures through C++
void reverse();
double_llist()
{
start = NULL;
}
};
/*
* Main: Conatins Menu
*/
int main()
{
int choice, element, position;
double_llist dl;
while (1)
{
cout<<endl<<" --------------------------- "<<endl;
cout<<endl<<"Operations on Doubly linked list"<<endl;
cout<<endl<<" --------------------------- "<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at begining"<<endl;
cout<<"3.Add after position"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Count"<<endl;
cout<<"7.Reverse"<<endl;
cout<<"8.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch ( choice )
{
case 1:
cout<<"Enter the element: ";
cin>>element;
dl.create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
dl.add_begin(element);
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
33
Data Structures through C++
/*
* Create Double Link List
*/
void double_llist::create_list(int value)
{
34
Data Structures through C++
/*
* Insertion at the beginning
*/
void double_llist::add_begin(int value)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->info = value;
temp->next = start;
start->prev = temp;
start = temp;
cout<<"Element Inserted"<<endl;
}
/*
* Insertion of element at a particular position
*/
void double_llist::add_after(int value, int pos)
{
if (start == NULL)
{
35
Data Structures through C++
/*
* Deletion of element from the list
*/
void double_llist::delete_element(int value)
{
struct node *tmp, *q;
/*first element deletion*/
if (start->info == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
36
Data Structures through C++
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{
/*Element deleted in between*/
if (q->next->info == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = q->next;
}
/*last element deleted*/
if (q->next->info == value)
{
tmp = q->next;
free(tmp);
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}
/*
* Display elements of Doubly Link List
*/
void double_llist::display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty,nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
37
Data Structures through C++
/*
* Number of elements in Doubly Link List
*/
void double_llist::count()
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q = q->next;
cnt++;
}
cout<<"Number of elements are: "<<cnt<<endl;
}
/*
* Reverse Doubly Link List
*/
void double_llist::reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}
38
Data Structures through C++
Output:
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 2
Enter the element: 100
First Create the list.
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 3
Enter the element: 200
Insert Element after postion: 1
First Create the list.
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 4
List empty,nothing to delete
39
Data Structures through C++
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
List empty,nothing to display
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 6
Number of elements are: 0
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 7
List empty,nothing to reverse
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
40
Data Structures through C++
8.Quit
Enter your choice : 1
Enter the element: 100
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
100 <-> NULL
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 2
Enter the element: 200
Element Inserted
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
200 <-> 100 <-> NULL
41
Data Structures through C++
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 3
Enter the element: 50
Insert Element after postion: 2
Element Inserted
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
200 <-> 100 <-> 50 <-> NULL
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 3
Enter the element: 150
Insert Element after postion: 3
Element Inserted
42
Data Structures through C++
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
200 <-> 100 <-> 50 <-> 150 <-> NULL
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 6
Number of elements are: 4
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 4
Enter the element for deletion: 50
Element Deleted
1.Create Node
2.Add at begining
3.Add after
4.Delete
43
Data Structures through C++
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
200 <-> 100 <-> 150 <-> NULL
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 6
Number of elements are: 3
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 7
List Reversed
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
44
Data Structures through C++
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 3
Enter the element: 200
Insert Element after postion: 100
There are less than 100 elements.
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 4
Enter the element for deletion: 150
Element Deleted
1.Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 5
The Doubly Link List is :
100 <-> 200 <-> NULL
45
Data Structures through C++
1. Create Node
2.Add at begining
3.Add after
4.Delete
5.Display
6.Count
7.Reverse
8.Quit
Enter your choice : 8
Viva Questions :
46
Data Structures through C++
3. Write a C++ program that uses stack operations to convert a given infix expression into its
postfix equivalent, Implement the stack using an array.
Algorithm:
Step 1: Define a stack array.
Step 2: Scan each character in the infix string
Step 3: If it is between 0 to 9 or any alphabet, append it to postfix string.
Step 4: If it is left parenthesis push to stack
If it is operator *,+,-,/,%,^ then
If the stack is empty push it to the stack
If the stack is not empty then start a loop:
If the top of the stack has higher precedence
Then pop and append to output string
Else break
Push to the stack
If it is right parenthesis then
While stack not empty and top not equal to left brace
Pop from stack and append to output string
Finally pop out the left brace.
Step 5: If there is any input in the stack pop and append to the Postfix string.
Source Code:
#include <iostream.h>
#include <string.h>
#include <ctype.h>
const int MAX = 50 ;
class infix
{
private :
char target[MAX], stack[MAX] ;
char *s, *t ;
int top ;
public :
infix( ) ;
void setexpr ( char *str ) ;
void push ( char c ) ;
char pop( ) ;
void convert( ) ;
int priority ( char c ) ;
void show( ) ;
};
infix :: infix( )
{
top = -1 ;
strcpy ( target, "" ) ;
strcpy ( stack, "" ) ;
47
Data Structures through C++
t = target ;
s = "" ;
}
void infix :: setexpr ( char *str )
{
s = str ;
}
void infix :: push ( char c )
{
if ( top == MAX )
cout << "\nStack is full\n" ;
else
{
top++ ;
stack[top] = c ;
}
}
char infix :: pop( )
{
if ( top == -1 )
{
cout << "\nStack is empty\n" ;
return -1 ;
}
else
{
char item = stack[top] ;
top-- ;
return item ;
}
}
void infix :: convert( )
{
while ( *s )
{
if ( *s == ' ' || *s == '\t' )
{
s++ ;
continue ;
}
if ( isdigit ( *s ) || isalpha ( *s ) )
{
while ( isdigit ( *s ) || isalpha ( *s ) )
{
*t = *s ;
s++ ;
48
Data Structures through C++
t++ ;
}
}
if ( *s == '(' )
{
push ( *s ) ;
s++ ;
}
char opr ;
if ( *s == '*' || *s == '+' || *s == '/' || *s == '%' || *s == '-' || *s == '$' )
{
if ( top != -1 )
{
opr = pop( ) ;
while ( priority ( opr ) >= priority ( *s ) )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
push ( opr ) ;
push ( *s ) ;
}
else
push ( *s ) ;
s++ ;
}
if ( *s == ')' )
{
opr = pop( ) ;
while ( ( opr ) != '(' )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
s++ ;
}
}
while ( top != -1 )
{
char opr = pop( ) ;
*t = opr ;
t++ ;
}
*t = '\0' ;
49
Data Structures through C++
}
int infix :: priority ( char c )
{
if ( c == '$' )
return 3 ;
if ( c == '*' || c == '/' || c == '%' )
return 2 ;
else
{
if ( c == '+' || c == '-' )
return 1 ;
else
return 0 ;
}
}
void infix :: show( )
{
cout << target ;
}
void main( )
{
char expr[MAX] ;
infix q ;
q.setexpr ( expr ) ;
q.convert( ) ;
Viva Questions:
1. What are the applications of stack?
2. List the types of conversions.
3. What is the inorder?
4. What is the postorder?
50
Data Structures through C++
4. Write a C++ program to implement a double ended queue ADT using an array, using a
doubly linked list.
Algorithm:
i) array
AIM: Implement a DEQUEUE using arrays
Algorithm for Insertion at rear end
Step -1: [Check for overflow]
if(rear==MAX)
Print("Queue is Overflow”);
return;
Step-2: [Insert element]
else
rear=rear+1;
q[rear]=no;
[Set rear and front pointer]
if rear=0
rear=1;
if front=0
front=1;
Step-3: return
Algorithm for Insertion at font end
Step-1 : [Check for the front position]
if(front<=1)
Print (“Cannot add item at front end”);
return;
Step-2 : [Insert at front]
else
front=front-1;
q[front]=no;
Step-3 : Return
Algorithm for Deletion from front end
Step-1 [ Check for front pointer]
if front=0
print(" Queue is Underflow”);
return;
Step-2 [Perform deletion]
else
no=q[front];
print(“Deleted element is”,no);
[Set front and rear pointer]
if front=rear
front=0;
rear=0;
else
front=front+1;
Step-3 : Return
51
Data Structures through C++
Source Code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class queue
{
int queue1[5];
int rear,front;
public:
queue()
{
rear=-1;
front=-1;
}
void insert(int x)
{
if(rear > 4)
{
cout <<"queue over flow";
front=rear=-1;
return;
}
queue1[++rear]=x;
cout <<"inserted" <<x;
}
void delet()
{
if(front==rear)
52
Data Structures through C++
{
cout <<"queue under flow";
return;
}
cout <<"deleted" <<queue1[++front];
}
void display()
{
if(rear==front)
{
cout <<" queue empty";
return;
}
for(int i=front+1;i<=rear;i++)
cout <<queue1[i]<<" ";
}
};
main()
{
int ch;
queue qu;
while(1)
{
cout <<"\n1.insert 2.delet 3.display 4.exit\nEnter ur choice";
cin >> ch;
switch(ch)
{
case 1: cout <<"enter the element";
cin >> ch;
qu.insert(ch);
break;
case 2: qu.delet(); break;
case 3: qu.display();break;
case 4: exit(0);
}
}
return (0);
}
Output:
1.insert 2.delet 3.display 4.exit
Enter ur choice1
enter the element21
inserted21
53
Data Structures through C++
Algorithm: display()
{
ptr = front; //assign the ptr to front node
if(front==NULL || rear==NULL)
{
printf("List is empty");
}
while(ptr != NULL)
{
Display ptr ->data
Pointer move to next node i.e: ptr = ptr->next;
}
}
Algorithm: insert_begin(x)
{
Allocate a memory for new node(new1)
new1 -> data =x;
new1 ->previous = new1 ->next =NULL;
if(front == NULL||rear==NULL)
54
Data Structures through C++
55
Data Structures through C++
Source Code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:
int data;
class node *next;
class node *prev;
};
56
Data Structures through C++
top2=0;
head=NULL;
tail=NULL;
}
void push(int x){
node *temp;
int ch;
if(top1+top2 >=5)
{
cout <<"dqueue overflow";
return ;
}
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 ur choice:";
cin >> ch;
if(ch==1)
{
top1++;
temp=new node;
temp->data=x;
temp->next=head;
temp->prev=NULL;
head->prev=temp;
head=temp;
}
else
{
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
57
Data Structures through C++
}
}
void pop()
{
int ch;
cout <<"Delete 1.First Node 2.Last Node\n Enter ur choice:";
cin >>ch;
if(top1 + top2 <=0)
{
cout <<"\nDqueue under flow";
return;
}
if(ch==1)
{
head=head->next;
head->prev=NULL;
top1--;
}
else
{
top2--;
tail=tail->prev;
tail->next=NULL;
}
}
void display()
{
int ch;
node *temp;
cout <<"display from 1.Staring 2.Ending\n Enter ur choice";
cin >>ch;
if(top1+top2 <=0)
{
cout <<"under flow";
return ;
}
if (ch==1)
{
temp=head;
while(temp!=NULL)
{
cout << temp->data <<" ";
temp=temp->next;
58
Data Structures through C++
}
}
else
{
temp=tail;
while( temp!=NULL)
{
cout <<temp->data << " ";
temp=temp->prev;
}
}
}
};
main()
{
dqueue d1;
int ch;
while (1){
cout <<"1.INSERT 2.DELETE 3.DISPLAU 4.EXIT\n Enter ur choice:";
cin >>ch;
switch(ch)
{
case 1: cout <<"enter element";
cin >> ch;
d1.push(ch); break;
case 2: d1.pop(); break;
case 3: d1.display(); break;
case 4: exit(1);
}
}}
OUTPUT
59
Data Structures through C++
Enter ur choice:3
display from 1.Staring 2.Ending
Enter ur choice1
546
Enter ur choice:2
Delete 1.First Node 2.Last Node
Enter ur choice:1
Enter ur choice:3
display from 1.Staring 2.Ending
Enter ur choice1
46
Viva Questions:
1. What is the double ended queue?
2. What are the applications of double ended queue?
3. Which data structure is used for double ended queue?
4. List the advantages of double ended queue over single queue.
5. List the disadvantages of double ended queue.
60
Data Structures through C++
Algorithm
61
Data Structures through C++
Source Code:
#include <iostream>
#include <deque>
#include <climits>
#include <vector>
using namespace std;
struct Tree
{
char data;
Tree *left;
Tree *right;
Tree *parent;
};
return node;
}
62
Data Structures through C++
if(node == NULL) {
retNode = newTreeNode(data);
retNode->parent = p;
return retNode;
}
if(data <= node->data ) {
p = node;
node->left = insertTreeNode(node->left,data);
}
else {
p = node;
node->right = insertTreeNode(node->right,data);
}
return node;
}
isBST(node->left);
isBST(node->right);
return;
}
63
Data Structures through C++
else
return treeSize(node->left) + 1 + treeSize(node->right);
}
/* Tree Minimum */
Tree* minTree(struct Tree *node)
{
if(node == NULL) return NULL;
while(node->left)
node = node -> left;
return node;
}
/* Tree Maximum */
64
Data Structures through C++
Tree *y = node->parent;
while(y != NULL && node == y->right) {
node = y;
y = y->parent;
}
return y;
}
Tree *y = node->parent;
/* if it does not have a left child,
predecessor is its first left ancestor */
while(y != NULL && node == y->left) {
node = y;
y = y->parent;
}
return y;
}
reverseOrderPrint(node->right);
65
Data Structures through C++
left = lowestCommonAncestor(node->left,p,q);
right = lowestCommonAncestor(node->right, p,q);
if(left && right)
return node;
else
return (left) ? left : right;
}
printTreeInOrder(node->left);
cout << node->data << " ";
printTreeInOrder(node->right);
}
66
Data Structures through C++
*/
void printTreePostOrder(struct Tree *node)
{
if(node == NULL) return;
printTreePostOrder(node->left);
printTreePostOrder(node->right);
cout << node->data << " ";
}
/* print in preorder */
/* 1. Visit the root.
2. Traverse the left subtree.
3. Traverse the right subtree.
*/
void printTreePreOrder(struct Tree *node)
{
if(node == NULL) return;
/* In reverse of printTreeInOrder() */
void printTreeReverseOrder(struct Tree *node)
{
if(node == NULL) return;
if(node->left == NULL && node->right == NULL) {
cout << node->data << " ";
return;
}
printTreeReverseOrder(node->right);
cout << node->data << " ";
printTreeReverseOrder(node->left);
}
/* recursion routine to find path */
void pathFinder(struct Tree *node, int path[], int level)
{
if(node == NULL) return;
// save leaf node
if(node->left == NULL && node->right == NULL) {
path[level] = node->data;
for(int i = 0; i <= level; i++) {
cout << (char)path[i];
67
Data Structures through C++
}
cout << endl;
return;
}
// save parent node
path[level] = node->data;
pathFinder(node->left, path, level+1);
pathFinder(node->right, path, level+1);
}
68
Data Structures through C++
Tree *tmp;
mirror(r->left);
mirror(r->right);
/* swap pointers */
tmp = r->right;
r->right = r->left;
r->left = tmp;
}
while (!queue.empty()) {
Tree *p = queue.front();
cout << p->data << " ";
queue.pop_front();
if (p->left != NULL)
69
Data Structures through C++
queue.push_back(p->left);
if (p->right != NULL)
queue.push_back(p->right);
}
cout << endl;
}
/* This code prints out all nodes at the same depth (level) */
void BreadthFirst_LevelElement_Print
(struct Tree *root, vector<vector<int> > &v;)
{
if(root == NULL) return;
deque<Tree *> q;
q.push_back(root);
while(!q.empty()) {
Tree *p = q.front();
int lev = getLevel(root, p->data, 0);
v[lev].push_back(p->data);
q.pop_front();
if(p->left) q.push_back(p->left);
if(p->right)q.push_back(p->right);
}
return;
}
/* levelPrint()
prints nodes at the same level
This is simpler than the BreadthFirstTraversal(root) above
It takes 2D vector with the same size of level (= MaxDepth+1)
and fills elements as we traverse (preOrder) */
70
Data Structures through C++
// leaf nodes
if(node->left == NULL && node->right == NULL) {
elm[level].push_back(node->data);
return;
}
// other nodes
elm[level++].push_back(node->data);
levelPrint(node->left, elm, level);
levelPrint(node->right, elm, level);
}
if(node){
TreeToArray(node->left,a);
a[pos++] = node->data;
TreeToArray(node->right,a);
}
}
while(!que.empty())
71
Data Structures through C++
{
struct Tree *p = que.front();
int level = getLevel(node, p->data, 0) ;
// even level
if (level % 2 == 0)
evenVec.push_back(p->data);
else
oddVec.push_back(p->data);
que.pop_front();
if(p->left) que.push_back(p->left);
if(p->right) que.push_back(p->right);
}
/* size of tree */
72
Data Structures through C++
/* max depth */
cout << "max depth = " << maxDepth(root) << endl;
/* min depth */
cout << "min depth = " << minDepth(root) << endl;
/* balanced tree? */
if(isBalanced(root))
cout << "This tree is balanced!\n";
else
cout << "This tree is not balanced!\n";
ch = 'B';
found = lookUp(root,ch);
if(found) {
cout << "Min value of subtree " << ch << " as a root is "
<< minTree(found)->data << endl;
cout << "Max value of subtree " << ch << " as a root is "
<< maxTree(found)->data << endl;
}
ch = 'B';
found = lookUp(root,ch);
if(found) {
succ = succesorInOrder(found);
if(succ)
cout << "In Order Successor of " << ch << " is "
<< succesorInOrder(found)->data << endl;
73
Data Structures through C++
else
cout << "In Order Successor of " << ch << " is None\n";
}
ch = 'E';
found = lookUp(root,ch);
if(found) {
succ = succesorInOrder(found);
if(succ)
cout << "In Order Successor of " << ch << " is "
<< succesorInOrder(found)->data << endl;
else
cout << "In Order Successor of " << ch << " is None\n";
}
ch = 'I';
found = lookUp(root,ch);
if(found) {
succ = succesorInOrder(found);
if(succ)
cout << "In Order Successor of " << ch << " is "
<< succesorInOrder(found)->data << endl;
else
cout << "In Order Successor of " << ch << " is None\n";
}
ch = 'B';
found = lookUp(root,ch);
if(found) {
pred = predecessorInOrder(found);
if(pred)
cout << "In Order Predecessor of " << ch << " is "
<< predecessorInOrder(found)->data << endl;
else
cout << "In Order Predecessor of " << ch << " is None\n";
}
ch = 'E';
found = lookUp(root,ch);
if(found) {
pred = predecessorInOrder(found);
if(pred)
cout << "In Order Predecessor of " << ch << " is "
<< predecessorInOrder(found)->data << endl;
else
cout << "In Order Predecessor of " << ch << " is None\n";
74
Data Structures through C++
ch = 'I';
found = lookUp(root,ch);
if(found) {
pred = predecessorInOrder(found);
if(pred)
cout << "In Order Predecessor of " << ch << " is "
<< predecessorInOrder(found)->data << endl;
else
cout << "In Order Predecessor of " << ch << " is None\n";
}
ch1 = 'E';
ch2 = 'H';
ancestor =
lowestCommonAncestor(root,
lookUp(root,ch1), lookUp(root,ch2));
if(ancestor)
cout << "The lowest common ancestor of " << ch1 << " and "
<< ch2 << " is " << ancestor->data << endl;
ch1 = 'D';
ch2 = 'E';
ancestor =
lowestCommonAncestor(root,
lookUp(root,ch1), lookUp(root,ch2));
if(ancestor)
cout << "The lowest common ancestor of " << ch1 << " and "
<< ch2 << " is " << ancestor->data << endl;
ch1 = 'G';
ch2 = 'I';
ancestor =
lowestCommonAncestor(root,
lookUp(root,ch1), lookUp(root,ch2));
75
Data Structures through C++
if(ancestor)
cout << "The lowest common ancestor of " << ch1 << " and "
<< ch2 << " is " << ancestor->data << endl;
ch1 = 'H';
ch2 = 'I';
ancestor =
lowestCommonAncestor(root,
lookUp(root,ch1), lookUp(root,ch2));
if(ancestor)
cout << "The lowest common ancestor of " << ch1 << " and "
<< ch2 << " is " << ancestor->data << endl;
/* lookUp */
ch = 'D';
found = lookUp(root,ch);
if(found)
cout << found->data << " is in the tree\n";
else
cout << ch << " is not in the tree\n";
/* lookUp */
ch = 'M';
found = lookUp(root,ch);
if(found)
cout << found->data << " is in the tree\n";
76
Data Structures through C++
else
cout << ch << " is not in the tree\n";
/* Traversing level-order.
We visit every node on a level before going to a lower level.
This is also called Breadth-first traversal.*/
cout << "printing with Breadth-first traversal" << endl;
BreadthFirstTraversal(root);
/* levelPrint()
prints nodes at the same level
This is simpler than the BreadthFirstTraversal(root) above
It takes 2D vector (elm) with the same size of level (= MaxDepth+1)
and fills elements as we traverse (preOrder) */
vector<vector<char> > elm;
int mxDepth = maxDepth(root);
elm.resize(mxDepth+1);
int level = 0;
levelPrint(root, elm, level);
cout << "levelPrint() " << endl;
for(int i = 0; i <= mxDepth; i++) {
cout << "level " << i << ": " ;
for(int j = 0; j < elm[i].size(); j++)
cout << elm[i][j] << " ";
cout << endl;
77
Data Structures through C++
/* subtree */
Tree *root2 = newTreeNode('D');
insertTreeNode(root2,'C');
insertTreeNode(root2,'E');
cout << "1-2 subtree: " << isSubTree(root, root2) << endl;
cout << "2-3 subtree: " << isSubTree(root2, root3) << endl;
cout << "3-2 subtree: " << isSubTree(root3, root2) << endl;
/* deleting a tree */
clear(root);
return 0;
}
78
Data Structures through C++
Output:
size = 9
max depth = 3
min depth = 2
This tree is balanced!
Min value = A
Max value = I
Node B is at level: 1
Node H is at level: 3
Node F is at level: 0
even level elements : F A D I
odd level elements : B G C E H
Min value of subtree B as a root is A
Max value of subtree B as a root is E
In Order Successor of B is C
In Order Successor of E is F
In Order Successor of I is None
In Order Predecessor of B is A
In Order Predecessor of E is D
In Order Predecessor of I is H
The lowest common ancestor of A and C is B
The lowest common ancestor of E and H is F
The lowest common ancestor of D and E is B
The lowest common ancestor of G and I is F
The lowest common ancestor of H and I is G
increasing sort order
ABCDEFGHI
post order
ACEDBHIGF
pre order
FBADCEGIH
reverse order
IHGFEDCBA
D is in the tree
M is not in the tree
printing paths ...
FBA
FBDC
FBDE
FGIH
5-th maximum data is E
printing with Breadth-first traversal
FBGADICEH
79
Data Structures through C++
Level at 0: F
Level at 1: B G
Level at 2: A D I
Level at 3: C E H
levelPrint()
level 0: F
level 1: B G
level 2: A D I
level 3: C E H
New array: A B C D E F G H I
New array: A B C D E F G H I
1-2 subtree: 1
1-3 subtree: 1
1-4 subtree: 0
2-3 subtree: 0
3-2 subtree: 1
Viva Questions:
1. What is meant by binary search tree?
2. List the properties of binary search tree.
3. List the traversals of binary search tree.
4. What are the applications of binary search tree.
5. What is the complete binary tree?
6. What is the full binary tree?
80
Data Structures through C++
6. .Write a C++ program that uses function templates to perform the following:
a) Search for a key element in a list of elements using linear search.
b) Search for a key element in a list of sorted elements using binary search.
Given a list L of n elements with values or records L0 ... Ln−1, and target value T, the following
subroutine uses binary search to find the index of the target T in L.
1. Set i to 0.
2. If Li = T, the search terminates successfully; return i.
3. Increase i by 1.
4. If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.
Source Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr[10], i, num, n, c=0, pos;
cout<<"Enter the array size : ";
cin>>n;
cout<<"Enter Array Elements : ";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be search : ";
cin>>num;
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
pos=i+1;
break;
}
}
if(c==0)
{
cout<<"Number not found..!!";
}
81
Data Structures through C++
else
{
cout<<num<<" found at position "<<pos;
}
getch();
}
Output:
b) Search for a key element in a list of sorted elements using binary search.
Algorithm:
Step 1: Start
Step 2: Initialize
low = 1
high = n
Step 3: Perform Search
While(low <= high)
Step 4: Obtain index of midpoint of interval
Middle = (low + high) / 2
Step 5: Compare
if(X < K[middle])
high = middle - 1
else
print “Element found at position”
Return(middle)
goto: step 2
Step 6: Unsuccessful Search
print “Element found at position”
Return (middle)
Step 7: Stop
82
Data Structures through C++
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, n, key, low, high, mid;
clrscr();
printf(“Enter the array elements in ascending order”);
for(i = 0; i < n; i++)
{
scanf(“%d”, &a[i]);
}
printf(“Enter the key element\n”);
scanf(“%d”, &key);
low = 0;
high = n - 1;
while(high >= low)
{
mid = (low + high) / 2;
if(key == a[mid])
break;
else
{
if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
}
if(key == a[mid])
printf(“The key element is found at location %d”, mid + 1);
else
printf(“the key element is not found”);
getch();
}
Output:
Enter the size of the array 7
Enter the array elements in ascending order 23 45 68 90 100 789 890
Enter the key element 789
The key Element is found at location 6
Viva Questions:
1. What is meant by linear search?
2. What is meant by binary search?
3. What are the applications of binary search?
4. What is the time complexity of liner search?
5. What is the time complexity of binary search?
83
Data Structures through C++
7. Write a C++ program that implements Insertion sort algorithm to arrange a list of integers in
ascending order.
Algorithm:
Insertion sort is another sorting technique used when sorting arrays. Unlike bubble sort, it uses much
less number of passes to sort an array. As the name suggests, sorting is done by inserting elements in
their proper order by comparing an element with the elements on either side. Hers is how it works.
Suppose we want to sort an array A with elements A[1],A[2] ... A[N]. Then,
Step 1 : A[1] by itself is trivially sorted.
Step 2 : A[2] is inserted either before or after A[1] so that A[1],A[2] are sorted.
Step 3 : A[3] is inserted into proper place in A[1],A[2],that is, before A[1], between A[1]
and A[2, or after A[2], so that A[1],A[2],A[3] is sorted.
The process keeps repeating until the array is fully sorted.
Source Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>
void isort(T a[],int n)
{
int i;
for(i=1;i<n;i++)
{
T t=a[i];
int j;
for(j=i-1;j>=0&&t<a[j];j--)
{
a[j+1]=a[j];
}
a[j+1]=t;
}
}
void main()
{
int a[100],i,n;
cout<<"Enter number of elements : ";
cin>>n;
cout<<"Enter elements (Use Spacebar as Separator)\n";
for(i=0;i<n;i++)
{
84
Data Structures through C++
cin>>a[i];
}
isort(a,n);
cout<<"After sorting the elements are\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\n";
}
system("pause");
Output:
5
7
9
24
45
Viva Questions:
85
Data Structures through C++
8. Write a template based C++ program that implements selection sort algorithm to arrange a list
of elements in descending order.
Algorithm:
Let the values be store in an array "a"
Let n = a.length
for ( i = 0 ; i < n ; i ++ )
{
min=a[i];
for(j=i+1;j<n;j++) //select the min of the rest of array
{
if(min>a[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=a[j];
}
}
2. Swap this element a[min] and a[i]
int temp=a[i] ;
a[i]=a[minat]; //swap
a[minat]=temp;
}
Source Code:
#include<iostream>
int main()
{
int i,j,n,loc,temp,min,a[30];
cout<<"Enter the number of elements:";
cin>>n;
cout<<"\nEnter the elements\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
86
Data Structures through C++
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
return 0;
}
Output:
Enter the number of elements: 6
Enter the elements
18 3 10 7 8 1
Sorted list is as follows
1 3 7 8 10 18
Viva Questions:
87
Data Structures through C++
9. Write a template based C++ program that implements Quick sort algorithm to arrange a list of
elements in ascending order.
Algorithm:
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions given array
around picked pivot. There are many different versions of quickSort that pick pivot in different ways.
1) Always pick first element as pivot.
2) Always pick last element as pivot (implemented below)
3) Pick a random element as pivot.
4) Pick median as pivot.
Key process in quickSort is partition(). Target of partitions is, given an array and an element x of array
as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before
x, and put all greater elements (greater than x) after x. All this should be done in linear time.
Partition Algorithm
There can be many ways to do partition, following code adopts the method given in CLRS book. The
logic is simple, we start from leftmost element and keep track of index of smaller (or equal to) elements
as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we
ignore current element.
Quick_Sort(a[],left,right)
{
i=left;
j=right;
pivot=left;
while(i<j)
{
while(a[i]<=a[pivot]&&i<=right)
i++;
while(a[j]>=a[pivot]&&j>left)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
if(i>j)
{
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
pivot=j;
}
if(left<pivot)
Quick_Sort(a,left,pivot-1);
if(right>pivot)
Quick_Sort(a,pivot+1,right);
}
88
Data Structures through C++
Source Code:
#include<iostream>
#include<conio.h>
using namespace std;
}
}
int main()
{
int a[100],n,l,h,i;
cout<<"Enter number of elements:";
cin>>n;
cout<<"Enter the elements (Use Space As A Separator):";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"\nInitial Array:\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
h=n-1;
l=0;
quick(l,h,a);
cout<<"\nAfter Sorting:\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
return 0;
}
Output:
Viva Questions:
90
Data Structures through C++
10. Write a C++ program that implements Heap sort algorithm for sorting a list of integers in
ascending order.
Algorithm:
Source Code:
/*
* C++ Program to Implement Heap Sort
*/
#include <iostream>
#include <conio.h>
using namespace std;
void max_heapify(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2*i;
while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j+1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j/2] = a[j];
j = 2*j;
}
}
a[j/2] = temp;
return;
}
void heapsort(int *a, int n)
{
int i, temp;
91
Data Structures through C++
92
Data Structures through C++
40
enter element5
6
enter element6
75
enter element7
36
sorted output
6
12
34
36
40
45
75
Viva Questions:
93
Data Structures through C++
11. Write a C++ program that implements Merge sort algorithm for sorting a list of integers in
ascending order
Algorithm:
Merge sort is based on the divide – and – conquer paradigm. Its worst - case running time has a lower
order of growth than insertion sort. Since we are dealing with sub - problems, we state each sub -
problem as sorting a sub – array A [ pr].
Initially, p= 1 and r=n , but these values change as we recurse through sub-problems.
To sort A[p..r]:
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split
A[p..r] into two sub-arrays A[p..q] and A[q+ 1 ..r], each containing about half of the elements
Of A[p..r]. That is, q is the halfway point of A[p..r].
2. Conquer Step Conquer by recursively sorting the two sub-arrays A[p..q] and A [q+ 1 ..r].
3. Combine Step Combine the elements back in A [p..r] by merging the two sorted sub-arrays
A[p..q] and A[q+ 1 ..r] into a sorted sequence. To accomplish this step, we will define a procedure
MERGE (A,p,q,r).
Note that the recursion bottoms out when the sub -array has just one element, so that it is trivially
sorted. To sort the entire sequence A[1 .. n], make the initial call to the procedure
MERGE-SORT (A, 1,n).MERGE-SORT (A,p,r)
Source Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>
void m_sort(T nos[],T t[],int l,int r);
template<class T>
void mergesort(T nos[],T t[],int asize)
{
m_sort<T>(nos,t,0,asize-1);
}
template<class T>
void m_sort(T nos[],T t[],int l,int r)
{
int mid;
if(r>l)
{
94
Data Structures through C++
mid=(r+l)/2;
m_sort(nos,t,l,mid);
m_sort(nos,t,mid+1,r);
merge(nos,t,l,mid+1,r);
}
}
template<class T>
void merge(T nos[],T t[],int l,int mid,int r)
{
int i,l_end,num_elements,t_pos;
l_end=mid-1;
t_pos=l;
num_elements=r-l+1;
while((l<=l_end)&&(mid<=r))
{
if(nos[l]<=nos[mid])//(kept -nos instead )
{
t[t_pos]=nos[l];
t_pos++;
l++;
}
else
{
t[t_pos]=nos[mid];
t_pos++;
mid++;
}
}
while(l<=l_end)
{
t[t_pos]=nos[l];
l++;
t_pos++;
}
while(mid<=r)
{
t[t_pos]=nos[mid];
mid++;
t_pos++;
}
for(i=0;i<=num_elements;i++)
{
nos[r]=t[r];
r--;
}
95
Data Structures through C++
int main()
{
int a[20],b[20],n;
cout<<"\nEnter The Total Number Of Elements:";
cin>>n;
cout<<"\nEnter "<<n<<" elements (Use Spacebar as separator) : ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(a,b,n);
system("pause");
return 0;
}
Output:
Enter the total number of elements 6
Enter 6 elements: 87 33 53 123 5 44
The sorted elements list is
5 33 44 53 87 123
Viva Questions:
1. What is meant by merge sort?
2. What is the best case time complexity of merge sort?
3. What is the average case time complexity of merge sort?
4. What is the worst case time complexity of merge sort?
5. What is the methodology followed by merge sort?
96
Data Structures through C++
12. Write a C++ program to implement all the functions of a dictionary (ADT) using hashing.
Algorithm:
Dictionary : A Dictionary is a collection of pairs of the form (K,V). where ‘K’ is a Key and ‘V’ is the value
associated with the key ‘k’. No two pairs in the dictionary have a same key.
The Following operations performed on a dictionary :
1. Determine whether or not the dictionary is empty
2. Determine the dictionary Size ( No of Pairs )
3. Find the pair with a specified key
4. Insert a pair into the dictionary
5. Delete or erase the pair into the specified key
Source Code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
# define max 10
typedef struct list
{
int data;
struct list *next;
} node_type;
node_type *ptr[max],*root[max],*temp[max];
class Dictionary
{
public:
int index;
Dictionary();
void insert(int);
void search(int);
void delete_ele(int);
};
Dictionary::Dictionary()
{
index=-1;
for(int i=0; i<max; i++)
{
97
Data Structures through C++
root[i]=NULL;
ptr[i]=NULL;
temp[i]=NULL;
}
}
void Dictionary::insert(int key)
{
index=int(key%max);
ptr[index]=(node_type*)malloc(sizeof(node_type));
ptr[index]->data=key;
if(root[index]==NULL)
{
root[index]=ptr[index];
root[index]->next=NULL;
temp[index]=ptr[index];
}
else
{
temp[index]=root[index];
while(temp[index]->next!=NULL)
temp[index]=temp[index]->next;
temp[index]->next=ptr[index];
}
}
void Dictionary::search(int key)
{
int flag=0;
index=int(key%max);
temp[index]=root[index];
while(temp[index]!=NULL)
{
if(temp[index]->data==key)
{
cout<<"\nSearch key is found!!";
flag=1;
break;
}
else temp[index]=temp[index]->next;
}
if (flag==0)
cout<<"\nsearch key not found. ..... ";
}
void Dictionary::delete_ele(int key)
{
index=int(key%max);
temp[index]=root[index];
98
Data Structures through C++
99
Data Structures through C++
cout<<"\nEnter y to Continue:";
cin>>c;
}
while(c=='y');
getch();
}
OUTPUT:
MENU:
1. Create
2. Search for a value
3.Delete an value
Enter your choice:1
Enter the number of elements to be inserted:3
Enter the elements to be inserted:12
23
56
Enter y to Continue:y
MENU:
1. Create
2. Search for a value
3.Delete an value
Enter your choice:2
Enter the element to be searched:23
Search key is found!!
Enter the element to be deleted:23
23 has been deleted.
Enter y to Continue:y
MENU:
1. Create
2. Search for a value
3.Delete an value
Enter your choice:
Viva Questions:
1. What is hashing?
2. What is dictionary ADT?
3. List the operations performed on dictionary ADT.
100
Data Structures through C++
13. Write a C++ program that implements Radix sort algorithm for sorting a list of integers in
ascending order
Algorithm:
1. Find the length of the number that has maximum number of digits.
2. Initialize i=0, Repeat the below procedure till the length equals i.
3. Fill the bucket with all the digits in ith position.
4. Sort out the digits according to the order.
5. If length=i, i=i*10, goto to step 3. Else go to step 5
6. Print the sorted array.
Source Code:
#include <algorithm>
#include <iostream>
#include <iterator>
101
Data Structures through C++
// test radix_sort
int main()
{
int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };
return 0;
}
Output:
Viva Questions:
1. What is meant by radix sort?
2. What is the best case time complexity of radix sort?
3. What is the average case time complexity of radix sort?
4. What is the worst case time complexity of radix sort?
5. Give the examples to radix sort?
102
Data Structures through C++
14. Write a C++ program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in inorder.
Source Code:
#include <iostream>
using namespace std;
// Node class
class Node {
int key;
Node* left;
Node* right;
public:
Node() { key=-1; left=NULL; right=NULL; };
103
Data Structures through C++
// Tree class
class Tree {
Node* root;
public:
Tree();
~Tree();
Node* Root() { return root; };
void addNode(int key);
void inOrder(Node* n);
void preOrder(Node* n);
void postOrder(Node* n);
private:
void addNode(int key, Node* leaf);
void freeNode(Node* leaf);
};
// Constructor
Tree::Tree() {
root = NULL;
}
// Destructor
Tree::~Tree() {
freeNode(root);
}
// Add a node
104
Data Structures through C++
105
Data Structures through C++
106
Data Structures through C++
OUTPUT:-
add root node ... 30
add other node ... 10
add other node ... 20
add other node ... 40
add other node ... 50
In order traversal
10 20 30 40 50
Pre order traversal
30 10 20 40 50
Post order traversal
20 10 50 40 30
107
Data Structures through C++
15. Write a C++ program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Search for an integer key in the above binary search tree non recursively.
c) Search for an integer key in the above binary search tree recursively.
Algorithm:
Algorithm: Insert(root, ele)
{
if tree is empty then insert a node as root node otherwise go to next step
if ele is less than the root node the insert left sub tree of root node
otherwise insert right sub tree of root node
}
Source Code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void insert(int,int );
void display(int);
int search(int);
int search1(int,int);
int tree[40],t=1,s,x,i;
main()
{
int ch,y;
for(i=1;i<40;i++)
tree[i]=-1;
while(1)
{
108
Data Structures through C++
int search(int s)
{
109
Data Structures through C++
if(t==1)
{
cout <<"no element in tree";
return -1;
}
if(tree[s]==-1)
return tree[s];
if(tree[s]>x)
search(2*s);
else if(tree[s]<x)
search(2*s+1);
else
return s;
}
void display(int s)
{
if(t==1)
{cout <<"no element in tree:";
return;}
for(int i=1;i<40;i++)
if(tree[i]==-1)
cout <<" ";
else cout <<tree[i];
return ;
}
OUTPUT
1. INSERT
2. DELETE
3. DISPLAY
4. SEARCH
110
Data Structures through C++
5. EXIT
Enter your choice:3
no element in tree:
0123456789011121314151617181920212223242526272829303132
1. INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
111