You are on page 1of 115

CMR ENGINEERING COLLEGE

(Approved By AICTE-New Delhi, Affiliated to JNTUH)


Kandlakoya(V), Medchal Road, Hyderabad-501401

Department of Computer Science &


Engineering

LAB MANUAL

Name of the Lab : Data Structure Through C++

Class : II Year I Sem

Branch : Computer Science & Engineering

Regulation : R16

A.Y. : 2017-18

1|Page
Vision of the Department

To produce globally competent and industry ready graduates in Computer Science &
Engineering by imparting quality education with a know-how of cutting edge technology and
holistic personality.

Mission of the Department

M1. To offer high quality education in Computer Science & Engineering in order to Build
core competence for the students by laying solid foundation in Applied Mathematics, and
program framework with a focus on concept building.

M2. The department promotes excellence in teaching, research, and collaborative


Activities to prepare students for professional career or higher studies.

M3. Creating intellectual environment for developing logical skills and problem solving
Strategies, thus to develop, able and proficient computer engineer to compete in the Current
global scenario.

2|Page
CS306ES: DATA STRUCTURES THROUGH C++ LAB
B.Tech. II Year I Sem. LTPC0032
Course Objectives:
 To write and execute programs in C++ to solve problems using data structures such as
arrays, linked lists, stacks, queues, trees, graphs, hash tables and search trees.
 To learn to write C++programs to implement various sorting and searching
algorithms
Course Outcomes:
 Able to identify the appropriate data structures and algorithms for solving real world
problems.
 Able to implement various kinds of searching and sorting techniques.
 Able to implement data structures such as stacks, queues, Search trees, and hash
tables to solve various computing problems.
1. Write a C++ program that uses functions to perform the following:
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 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 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, using a
doubly linked list.
5. Write a C++ program that uses functions to perform the following:
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:
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 of integers
in ascending order.
8. Write a template based C++ program that implements selection sort algorithm to arrange a
list of elements in descending order.
9. Write a template based C++ program that implements Quick sort algorithm to arrange a list
of elements in ascending order.
10. Write a C++ program that implements Heap sort algorithm for sorting a list of integers in
ascending order.
11. Write a C++ program that implements Merge sort algorithm for sorting a list of integers
in ascending order
12. Write a C++ program to implement all the functions of a dictionary (ADT) using hashing.
13. Write a C++ program that implements Radix sort algorithm for sorting a list of integers in
ascending order
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.
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.

3|Page
REFERENCE BOOKS
1. Data Structures using C++, D. S. Malik, 2nd edition, Cengage learning.
2. Data Structures using C++, V. Patil, Oxford University Press.
3. Fundamentals of Data structures in C++, 2nd edition, E. Horowitz, S. Sahni and D.
Mehta, Universities Press.
4. C++ Plus Data Structures, 4th edition, Nell Dale, Jones and Bartlett student edition

S. No. List of Experiments Page No.


1 Write a C++ program that uses functions to perform the following:
a) Create a singly linked list of integers. 1-5
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 following: 6-20
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 expression into its
postfix equivalent, Implement the stack using an array. 21-23
4 Write a C++ program to implement a double ended queue ADT using an array, using a
doubly linked list. 24-42
5 Write a C++ program that uses functions to perform the following:
a) Create a binary search tree of characters. 43-53
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:
a) Search for a key element in a list of elements using linear search. 54-55
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 of integers
in ascending order. 56-57
8 Write a template based C++ program that implements selection sort algorithm to arrange a
list of elements in descending order 58-59
9 Write a template based C++ program that implements Quick sort algorithm to arrange a list 60-62
of elements in ascending order.
10 Write a C++ program that implements Heap sort algorithm for sorting a list of integers in
ascending order. 63-66
11 Write a C++ program that implements Merge sort algorithm for sorting a list of integers in
ascending order. 67-69
12 Write a C++ program to implement all the functions of a dictionary (ADT) using hashing. 70-74
13 Write a C++ program that implements Radix sort algorithm for sorting a list of integers in
ascending order. 75-76
14 Write a C++ program that uses functions to perform the following: 77-85
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:
a) Create a binary search tree of integers. 86-98
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.
1. Write a C++ program that uses functions to perform the following:

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

/*
* 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;
}
};

/*
* Main :contains menu
*/
main()
{
int choice, nodes, element, position, i;

5|Page
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();
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;

6|Page
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;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}

/*
* Inserting element in beginning
*/
void single_llist::insert_begin()
{

7|Page
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)
{
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: ";

8|Page
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++)
{
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;

9|Page
}
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;
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;

10 | P a g e
}
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)
{
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;
}

/*

11 | P a g e
* 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;
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)

12 | P a g e
{
ptr1 = ptr2;
ptr2 = ptr3;
ptr3 = ptr3->next;
ptr2->next = ptr1;
}
start = ptr2;
}

/*
* Display Elements of a link list
*/
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
---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
The List is Empty.

---------------------------------

13 | P a g e
Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 5
Delete a particular node:
List is empty

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 6
Update Node Value:
List is empty

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 7
Search element in Link List:
List is empty

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last

14 | P a g e
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 3
Inserting Node at a given position:
Enter the value to be inserted: 1010
Enter the postion at which node to be inserted: 5
Positon out of range

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 1
Inserting Node at Beginning:
Enter the value to be inserted: 100
Element Inserted at beginning

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 1
Inserting Node at Beginning:
Enter the value to be inserted: 200
Element Inserted at beginning

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position

15 | P a g e
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 2
Inserting node at last:
Enter the value to be inserted: 50
Element Inserted at last

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 2
Inserting node at last:
Enter the value to be inserted: 150
Element Inserted at last

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element

16 | P a g e
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->50->150->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 3
Inserting node at a given position:
Enter the value to be inserted: 1111
Enter the position at which node to be inserted: 4

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->50->1111->150->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit

17 | P a g e
Enter your choice : 3
Inserting node at a given position:
Enter the value to be inserted: 1010
Enter the position at which node to be inserted: 100
Position out of range

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->50->1111->150->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 5
Delete a Particular node:
Enter the position of value to be deleted: 1

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
100->50->1111->150->NULL

18 | P a g e
---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 6
Update Node Value:
Enter the node position to be updated: 1
Enter the new value: 1010
Node Updated

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
1010->50->1111->150->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 7
Search element in Link List:
Enter the value to be searched: 50
Element 50 is found at position 2

19 | P a g e
---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 9
Reverse elements of Link List

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
150->1111->50->1010->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 4
Sort Link List:

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position

20 | P a g e
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
50->150->1010->1111->NULL

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 10
Exiting...

*/

21 | P a g e
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.

/*
* 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();
void reverse();
double_llist()
{
start = NULL;
}
};

/*
* Main: Conatins Menu
*/
int main()
{

22 | P a g e
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;
cout<<"Insert Element after postion: ";
cin>>position;
dl.add_after(element, position);
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"List empty,nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
dl.delete_element(element);
cout<<endl;
break;

23 | P a g e
case 5:
dl.display_dlist();
cout<<endl;
break;
case 6:
dl.count();
break;
case 7:
if (start == NULL)
{
cout<<"List empty,nothing to reverse"<<endl;
break;
}
dl.reverse();
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}

/*
* Create Double Link List
*/
void double_llist::create_list(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}

/*

24 | P a g e
* 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)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->info = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;

25 | P a g e
}
else
{
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
}
cout<<"Element Inserted"<<endl;
}

/*
* 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;
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;

26 | P a g e
}
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)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}

/*
* 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;

27 | P a g e
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}

$ g++ doubly_llist.cpp
$ a.out
---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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.

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 3
Enter the element: 200
Insert Element after position: 1
First Create the list.

28 | P a g e
---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 4
List empty, nothing to delete

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 5
List empty, nothing to display

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 6
Numbers of elements are: 0

---------------------------------

29 | P a g e
Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 7
List empty, nothing to reverse

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 1
Enter the element: 100

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 5
The Doubly Link List is:
100 <-> NULL

30 | P a g e
---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 2
Enter the element: 200
Element Inserted

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 3

31 | P a g e
Enter the element: 50
Insert Element after position: 2
Element Inserted

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 3
Enter the element: 150
Insert Element after position: 3
Element Inserted

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after

32 | P a g e
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice : 5
The Doubly Link List is :
200 <-> 100 <-> 50 <-> 150 <-> NULL

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 6
Numbers of elements are: 4

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node

33 | P a g e
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 5
The Doubly Link List is:
200 <-> 100 <-> 150 <-> NULL

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 6
Numbers of elements are: 3

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 7
List Reversed

---------------------------------

Operations on Doubly linked list

---------------------------------

34 | P a g e
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 5
The Doubly Link List is:
150 <-> 100 <-> 200 <-> NULL

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 3
Enter the element: 200
Insert Element after position: 100
There are less than 100 elements.

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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

35 | P a g e
---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
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

---------------------------------

Operations on Doubly linked list

---------------------------------
1. Create Node
2. Add at beginning
3. Add after
4. Delete
5. Display
6. Count
7. Reverse
8. Quit
Enter your choice: 8

------------------
(Program exited with code: 1)
Press return to continue

36 | P a g e
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.

Program:
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;

// get weight of operators as per precedence


// higher weight given to operators with higher precedence
// for non operators, return 0
int getWeight(char ch) {
switch (ch) {
case '/':
case '*': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}

// convert infix expression to postfix using a stack


void infix2postfix(char infix[], char postfix[], int size) {
stack<char> s;
int weight;
int i = 0;
int k = 0;
char ch;
// iterate over the infix expression
while (i < size) {
ch = infix[i];
if (ch == '(') {
// simply push the opening parenthesis
s.push(ch);
i++;
continue;
}
if (ch == ')') {
// if we see a closing parenthesis,
// pop of all the elements and append it to
// the postfix expression till we encounter
// a opening parenthesis
while (!s.empty() && s.top() != '(') {
postfix[k++] = s.top();
s.pop();

}
// pop off the opening parenthesis also
if (!s.empty()) {
s.pop();
}
i++;

37 | P a g e
continue;
}
weight = getWeight(ch);
if (weight == 0) {
// we saw an operand
// simply append it to postfix expression
postfix[k++] = ch;

}
else {
// we saw an operator
if (s.empty()) {
// simply push the operator onto stack if
// stack is empty
s.push(ch);
}
else {
// pop of all the operators from the stack and
// append it to the postfix expression till we
// see an operator with a lower precedence that
// the current operator
while (!s.empty() && s.top() != '(' &&
weight <= getWeight(s.top())) {
postfix[k++] = s.top();
s.pop();

}
// push the current operator onto stack
s.push(ch);
}
}
i++;
}
// pop of the remaining operators present in the stack
// and append it to postfix expression
while (!s.empty()) {
postfix[k++] = s.top();
s.pop();
}
postfix[k] = 0; // null terminate the postfix expression
}

// main
int main() {
char infix[] = "A*(B+C)/D";
int size = strlen(infix);
char postfix[size];
infix2postfix(infix,postfix,size);
cout<<"\nInfix Expression :: "<<infix;
cout<<"\nPostfix Expression :: "<<postfix;
cout<<endl;
return 0;
}
/*OUTPUT:

38 | P a g e
Infix Expression :: A*(B+C)/D
Postfix Expression :: ABC+*D/

*/

39 | P a g e
4. Write a C++ program to implement a double ended queue ADT using an array, using a

doubly linked list.

Write C programs to implement a double ended queue ADT using i)array and ii)doubly
linked list respectively.

Double-Ended Queue

A double-ended queue is an abstract data type similar to an simple queue, it allows you to
insert and delete from both sides means items can be added or deleted from the front or rear
end.

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

40 | P a g e
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:[Performdeletion]
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

41 | P a g e
Algorithm for Deletion from rear end

Step-1 :[Check for the rear pointer]


if rear=0

print(“Cannot delete value at rear end”);


return;

Step-2:[ perform deletion]


else
no=q[rear];

[Check for the front and rear pointer]


if front= rear

front=0;
rear=0;
else
rear=rear-1;
print(“Deleted element is”,no);
Step-3 : Return

42 | P a g e
Program:
#include<iostream>
using namespace std;
#define SIZE 5
class dequeue
{
int a[10],front,rear;
public:
dequeue();
void add_at_beg(int);
void add_at_end(int);
void delete_fr_front();
void delete_fr_rear();
void display();
};
dequeue::dequeue()
{
front=-1;
rear=-1;
}
void dequeue::add_at_end(int item)
{

if(rear>=SIZE-1)
{
cout<<"\n insertion is not posibble,overflow!!!!";
}
else
{
if(front==-1)
{
front++;
rear++;
}
else
{
rear=rear+1;
}
a[rear]=item;
cout<<"\nInserted item is"<<a[rear];
}
}
void dequeue::add_at_beg(int item)
{

if(front==-1)
{
front=0;
a[++rear]=item;
cout<<"\n inserted element is"<<item;
}
else if(front!=0)
{
a[--front]=item;
cout<<"\n inserted element is"<<item;

}
else
{
cout<<"\n insertion is not posibble,overflow!!!";
}

43 | P a g e
}
void dequeue::display()
{
if(front==-1)
{
cout<<"Dequeue is empty";
}
else
{
for(int i=front;i<=rear;i++)
{
cout<<a[i]<<" ";
}
}
}
void dequeue::delete_fr_front()
{
if(front==-1)
{
cout<<"deletion is not possible::dequeue is empty";
return;
}
else
{
cout<<"the deleted element is"<<a[front];
if(front==rear)
{
front=rear=-1;
return;
}
else
front=front+1;
}
}
void dequeue::delete_fr_rear()
{
if(front==-1)
{
cout<<"deletion is not possible::dequeue is empty";
return;
}
else
{
cout<<"the deleted element is"<<a[rear];
if(front==rear)
{
front=rear=-1;
}
else
rear=rear-1;
}
}
int main()
{
int c,item;
dequeue d1;
do
{
cout<<"\n\n***DEQUEUE OPERATION***\n";
cout<<"\n 1_insert at beginning";
cout<<"\n 2_insert at end";
cout<<"\n 3_display";
cout<<"\n 4_deletion from front";
cout<<"\n 5_deletion from rear";
cout<<"\n 6_exit";

44 | P a g e
cout<<"\n enter your choice";
cin>>c;
switch(c)
{
case 1:cout<<"enter the element to be inserted";
cin>>item;
d1.add_at_beg(item);
break;
case 2:cout<<"enter the element to be inserted";
cin>>item;
d1.add_at_end(item);
break;
case 3:d1.display();
break;
case 4:d1.delete_fr_front();
break;
case 5:d1.delete_fr_rear();
break;
case 6:exit(1);
break;
csdefault:cout<<"invalid choice";
break;
}
}
while(c!=7);
}

OUTPUT:

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice1
enter the element to be inserted10

inserted element is10

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice1
enter the element to be inserted20

insertion is not posibble,overflow!!!

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear

45 | P a g e
6_exit
enter your choice2
enter the element to be inserted20

Inserted item is20

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice3
10 20

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice2
enter the element to be inserted30

Inserted item is30

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice3
10 20 30

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice4
the deleted element is10

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice3
20 30

***DEQUEUE OPERATION***

46 | P a g e
1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice5
the deleted element is30

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice3
20

***DEQUEUE OPERATION***

1_insert at beginning
2_insert at end
3_display
4_deletion from front
5_deletion from rear
6_exit
enter your choice

ii) Linked List

AIM: To implement a Double ended Queue using Linked List

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;
}

47 | P a g e
}

Algorithm: insert_begin(x)
{
Allocate a memory for new
node(new1) new1 -> data =x;
new1 ->previous = new1 ->next
=NULL;

if(front == NULL||rear==NULL)

front = rear = new1;


else

{
new1 ->next = front;
front ->previous = new1;
front = new1;

}
}
Algorithm: insert_last(x)
{

Allocate a memory for new node


(new1) new1 ->data = x;

new1 -> previous = new1 ->next =


NULL;
if (front == NULL||rear==NULL)

front = rear = new1;


else
{
rear ->next = new1;
new1 ->previous = rear;
rear = new1;

48 | P a g e
}
}

Algorithm: delete_begin()
{
if (front == NULL || rear==NULL)
{
Display List is empty

}
else
{
temp = front;/*assign the temp point at front node*/
x= temp->data;
if(front==rear)//verify list having only one node then update the list is empty
{
front=NULL;
rear=NULL;
}
else
{
front = front->next;
front->previous=NULL;

count --; // decrease the no.of nodes in the list delete


the temp node

}
}
Algorithm: delete_last( )

49 | P a g e
{
if(rear == NULL || front==NULL)
{
Display List is empty }
else
{
temp = rear;/*assign the temp point at rear node*/
if(front==rear)//verify list having only one node then update the list is empty
{
front=NULL;
rear=NULL;

}
else
{

rear = rear->previous;

rear -> next = NULL;

}
x= temp ->data;
delete the temp node
count --; // decrease the no.of nodes in the list return x;
}
}

50 | P a g e
Program:

/* Write C++ program to implement the double ended queue using a linked list */
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;

class node
{
public:
int data;
class node *next;
class node *prev;
};

class dqueue: public node


{
node *head,*tail;
int top1,top2;
public:
dqueue()
{
top1=0;
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
{

51 | P a g e
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
}

}
}
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;
}
}
else
{
temp=tail;
while( temp!=NULL)
{
cout <<temp->data << " ";
temp=temp->prev;
}
}
}

52 | P a g e
};

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:

1.INSERT 2.DELETE 3.DISPLAU 4.EXIT


Enter ur choice:1
enter element6
Add element 1.FIRST 2.LAST
enter ur choice:2

1.INSERT 2.DELETE 3.DISPLAU 4.EXIT

Enter ur choice:3
display from 1.Staring 2.Ending
Enter ur choice1
546
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT

Enter ur choice:2
Delete 1.First Node 2.Last Node
Enter ur choice:1

1.INSERT 2.DELETE 3.DISPLAU 4.EXIT

Enter ur choice:3
display from 1.Staring 2.Ending

Enter ur choice1
46

1.INSERT 2.DELETE 3.DISPLAU 4.EXIT


Enter ur choice:4*/

53 | P a g e
5. Write a C++ program that uses functions to perform the following:

a) Create a binary search tree of characters.

b) Traverse the above Binary search tree recursively in preorder, in order and post order
Definition. A binary search tree (BST) is a binary tree where each node has a Comparable
key (and an associated value) and satisfies the restriction that the key in any node is larger
than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in
that node's right subtree.
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

}
Algorithm: inorder(struct node *ptr)
{
if(ptr==NULL)
return;
else
{

Visit inorder(ptr->left)
diplay ptr->data

Visit inorder(ptr->right)
}
}
Algorithm: preorder(struct node *ptr)
{
if(ptr==NULL)
return;
else

54 | P a g e
{
Display ptr->data

Visit preorder(ptr->left)
Visit preorder(ptr->right)

}
}
Algorithm: postorder(ptr)

{
if(ptr==NULL)
return;
else
{
Visit postorder(ptr->left);
Visity postorder(ptr->right);
display ptr->data);

}
}

55 | P a g e
Program
/*BST*/

1. /*
* C++ Program To Implement BST
*/
# include <iostream>
# include <cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *left;
struct node *right;
}*root;

/*
* Class Declaration
*/
class BST
{
public:
void find(int, node **, node **);
void insert(int);
void del(int);
void case_a(node *,node *);
void case_b(node *,node *);
void case_c(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
void display(node *, int);
BST()
{
root = NULL;
}
};
/*
* Main Contains Menu
*/
int main()
{
int choice, num;
BST bst;

56 | P a g e
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 : ";
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);
break;
case 3:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal of BST:"<<endl;
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);

57 | P a g e
cout<<endl;
break;
case 7:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}

/*
* Find Element in the Tree
*/
void BST::find(int item, node **par, node **loc)
{
node *ptr, *ptrsave;
if (root == NULL)
{
*loc = NULL;
*par = NULL;
return;
}
if (item == root->info)
{
*loc = root;
*par = NULL;
return;
}
if (item < root->info)
ptr = root->left;
else
ptr = root->right;
ptrsave = root;
while (ptr != NULL)
{
if (item == ptr->info)
{
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (item < ptr->info)
ptr = ptr->left;
else
ptr = ptr->right;
}
*loc = NULL;
*par = ptrsave;
}

58 | P a g e
/*
* Inserting Element into the Tree
*/
void BST::insert(node *tree, node *newnode)
{
if (root == NULL)
{
root = new node;
root->info = newnode->info;
root->left = NULL;
root->right = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}

59 | P a g e
}

/*
* Delete Element from the tree
*/
void BST::del(int item)
{
node *parent, *location;
if (root == NULL)
{
cout<<"Tree empty"<<endl;
return;
}
find(item, &parent, &location);
if (location == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (location->left == NULL && location->right == NULL)
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;
}
else
{
if (loc == par->left)
par->left = NULL;
else
par->right = NULL;
}
}

/*
* Case B

60 | P a g e
*/
void BST::case_b(node *par, node *loc)
{
node *child;
if (loc->left != NULL)
child = loc->left;
else
child = loc->right;
if (par == NULL)
{
root = child;
}
else
{
if (loc == par->left)
par->left = child;
else
par->right = child;
}
}

/*
* Case C
*/
void BST::case_c(node *par, node *loc)
{
node *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->right;
while (ptr->left != NULL)
{
ptrsave = ptr;
ptr = ptr->left;
}
suc = ptr;
parsuc = ptrsave;
if (suc->left == NULL && suc->right == NULL)
case_a(parsuc, suc);
else
case_b(parsuc, suc);
if (par == NULL)
{
root = suc;
}
else
{
if (loc == par->left)
par->left = suc;
else
par->right = suc;

61 | P a g e
}
suc->left = loc->left;
suc->right = loc->right;
}

/*
* Pre Order Traversal
*/
void BST::preorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}
/*
* In Order Traversal
*/
void BST::inorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->info<<" ";
inorder(ptr->right);
}
}

/*
* Postorder Traversal
*/
void BST::postorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}

62 | P a g e
if (ptr != NULL)
{
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->info<<" ";
}
}

/*
* Display Tree Structure
*/
void BST::display(node *ptr, int level)
{
int i;
if (ptr != NULL)
{
display(ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
display(ptr->left, level+1);
}
}

/* Output
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 8
Root Node is Added
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

63 | P a g e
Root->: 8
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 9
Node Added To Right
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

9
Root->: 8
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 5
Node Added To Left
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

9
Root->: 8
5
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal

64 | P a g e
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 11
Node Added To Right
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

11
9
Root->: 8
5
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 3
Node Added To Left
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 7
Node Added To Right
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

11
9

65 | P a g e
Root->: 8
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 10
Node Added To Left
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

11
10
9
Root->: 8
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 2
Enter the number to be deleted : 10
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

11
9
Root->: 8

66 | P a g e
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 3
Inorder Traversal of BST:
3 5 7 8 9 11
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 4
Preorder Traversal of BST:
8 5 3 7 9 11
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 5
Postorder Traversal of BST:
3 7 5 11 9 8
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 2
Enter the number to be deleted : 8
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6

67 | P a g e
Display BST:

11
Root->: 9
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 10
Node Added To Left
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

11
10
Root->: 9
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 1
Enter the number to be inserted : 15
Node Added To Right
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

68 | P a g e
15
11
10
Root->: 9
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 4
Preorder Traversal of BST:
9 5 3 7 11 10 15
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 5
Postorder Traversal of BST:
3 7 5 10 15 11 9
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 6
Display BST:

15
11
10
Root->: 9
7
5
3
-----------------
Operations on BST
-----------------
1.Insert Element
2.Delete Element
3.Inorder Traversal
4.Preorder Traversal
5.Postorder Traversal
6.Display
7.Quit
Enter your choice : 7

69 | P a g e
------------------
(program exited with code: 1)
Press return to continue

*/

70 | P a g e
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.

#include<iostream>

using namespace std;

template <class T>


void Lsearch(T *a, T item, int n)
{
int z=0;
for(int i=0;i<n;i++)
{
if(a[i]== item)
{
z=1;
cout<<"\n Item found at position = "<<i+1<<"\n\n";
}
else
if(z!=1)
{
z=0;
}
}

if(z==0)
cout<<"\n Item not found in the list\n\n";
}

template <class T>


void Bsearch(T *a, T item, int n)
{
int beg=0,end=n-1;
int mid=beg+end/2;

while((a[mid]!=item) && (n>0))


{
if(item>a[mid])
beg=mid;
else
end=mid;

71 | P a g e
mid=(beg+end)/2;
n--;
}

if(a[mid]==item)
cout<<"\n Item found at position = "<<mid+1<<"\n\n";
else
cout<<"\n Item not found in the list\n\n";

void main()
{
int iarr[10] = {2,42,56,86,87,99,323,546,767,886};
double darr[6]= {2.4, 5.53,44.4, 54.45, 65.7,89.54};
int iele;
double dele;

cout<<"\n Elements of Integer Array \n";


for(int i=0;i<10;i++)
{
cout<<" "<<iarr[i]<<" ,";
}
cout<<"\n\n Enter an item to be search: ";
cin>>iele;
cout<<"\n\n Linear Search Method\n";
Lsearch(iarr,iele,10);
cout<<"\n\n Binary Search method\n";
Bsearch(iarr,iele,10);

cout<<"\n Elements of double Array \n";


for(int i=0;i<6;i++)
{
cout<<" "<<darr[i]<<" ,";
}
cout<<"\n\n Enter an item to be search: ";
cin>>dele;
cout<<"\n\n Linear Search Method\n";
Lsearch(darr,dele,6);
cout<<"\n\n Binary Search method\n";
Bsearch(darr,dele,6);
system("pause");
}

72 | P a g e
7. Write a C++ program that implements Insertion sort algorithm to arrange a list of integers

in ascending order.

Algorithm:

Insertion_Sort(a[], n)

for(i=1;i<n;j++)

k=a[i]; for(j=i-1;j>=0&&k<a[j];j--)

a[j+1]=a[j];

a[j+1]=k;

Program:

#include <iostream>

using namespace std;

// A structure to represent a node.


struct list
{
int data;
list *next;
};

// Function implementing insertion sort.


list* InsertinList(list *head, int n)
{
// Creating newnode and temp node.
list *newnode = new list;
list *temp = new list;

// Using newnode as the node to be inserted in the list.


newnode->data = n;
newnode->next = NULL;

// If head is null then assign new node to head.


if(head == NULL)
{
head = newnode;
return head;
}
else
{

73 | P a g e
temp = head;

// If newnode->data is lesser than head->data, then insert newnode before head.


if(newnode->data < head->data)
{
newnode->next = head;
head = newnode;
return head;
}

// Traverse the list till we get value more than newnode->data.


while(temp->next != NULL)
{
if(newnode->data < (temp->next)->data)
break;

temp=temp->next;
}

// Insert newnode after temp.


newnode->next = temp->next;
temp->next = newnode;
return head;
}
}

int main()
{
int n, i, num;
// Declaring head of the linked list.
list *head = new list;
head = NULL;

cout<<"\nEnter the number of data element to be sorted: ";


cin>>n;

for(i = 0; i < n; i++)


{
cout<<"Enter element "<<i+1<<": ";
cin>>num;
// Inserting num in the list.
head = InsertinList(head, num);
}

// Display the sorted data.


cout<<"\nSorted Data ";
while(head != NULL)
{
cout<<"->"<<head->data;
head = head->next;
}

return 0;
}

/* Output
Case 1:(average case)

Enter the number of data element to be sorted: 5


Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206

74 | P a g e
Sorted Data ->2->35->451->998->1206

Case 2:(best case)

Enter the number of data element to be sorted: 5


Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1

Sorted Data ->1->86->332->564->99845

case 3: (worst case)

Enter the number of data element to be sorted: 5


Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565

Sorted Data ->2->332->456->1024->16565

*/

8. Write a template based C++ program that implements selection sort algorithm to arrange a

list of elements in descending order.

#include<iostream>
#include<conio.h>

using namespace std;

template <class T>


void s_sort(T a[],int n)
{
int i,j,t;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i]) //for descending order use if(a[j]>a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}

75 | P a g e
int main()
{
int a[100],i,n;
cout<<"Enter The number of Element:\n";
cin>>n;
cout<<"\nEnter Elements:\n";
for(i=0;i<n;i++)
{

cout<<"\nEnter:";
cin>>a[i];
}
s_sort(a,n);
cout<<"\nAfter Sorting\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
return 0;
}/*OUTPUT:

Enter the no.of elements : 5

Enter element : 8

Enter element : 4

Enter element : 6

Enter element : 2

Enter element : 3

Before Sorting array elements are: 8 4 6 2 3

after Sorting array elements are : 2 3 4 6 8 */

76 | P a g e
9. Write a template based C++ program that implements Quick sort algorithm to arrange a list

of elements in ascending order.

#include<iostream>
#include<conio.h>
using namespace std;

//Function for partitioning array


int part(int low,int high,int *a)
{
int i,h=high,l=low,p,t; //p==pivot
p=a[low];
while(low<high)
{
while(a[l]<p)
{
l++;
}
while(a[h]>p)
{
h--;
}
if(l<h)
{
t=a[l];
a[l]=a[h];
a[h]=t;
}
else
{
t=p;
p=a[l];
a[l]=t;
break;
}
}
return h;
}

void quick(int l,int h,int *a)


{
int index,i;
if(l<h)
{
index=part(l,h,a);
quick(l,index-1,a);
quick(index+1,h,a);
}
}

int main()

77 | P a g e
{
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:

Enter the no.of elements : 5

Enter element : 8

Enter element : 4

Enter element : 6

Enter element : 2

Enter element : 3

Initial Array : 8 4 6 2 3

after Sorting : 2 3 4 6 8 */

78 | P a g e
10. Write a C++ program that implements Heap sort algorithm for sorting a list of

integers in ascending order.

Program:

#include <iostream>

using namespace std;

// A function to heapify the array.


void MaxHeapify(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;
// Break if parent value is already greater than child value.
if (temp > a[j])
break;
// Switching value with the parent node if temp < a[j].
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;
for (i = n; i >= 2; i--)
{
// Storing maximum value at the end.
temp = a[i];
a[i] = a[1];
a[1] = temp;
// Building max heap of remaining element.
MaxHeapify(a, 1, i - 1);
}
}
void Build_MaxHeap(int a[], int n)
{
int i;
for(i = n/2; i >= 1; i--)
MaxHeapify(a, i, n);
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i = 1; i < n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];

79 | P a g e
}
// Building max heap.
Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";

for (i = 1; i < n; i++)


cout<<"->"<<arr[i];

return 0;
}

Output

Enter the number of data element to be sorted: 10


Enter element 1: 9
Enter element 2: 6
Enter element 3: 4
Enter element 4: 3
Enter element 5: 8
Enter element 6: 7
Enter element 7: 5
Enter element 8: 2
Enter element 9: 0
Enter element 10: 1

Sorted Data ->0->1->2->3->4->5->6->7->8->9

11. AIM:Write a C++ program that implements Merge sort algorithm for sorting a list

of integers in ascending order*/

#include<iostream>

#include<conio.h>

using namespace std;

void mergesort(int *,int,int);

void merge(int *,int,int,int);

int a[20],i,n,b[20];

main()

cout <<"\n enter no of elements";

cin >> n;

cout <<"enter the elements";

for(i=0;i<n;i++)

cin >> a[i];

80 | P a g e
mergesort(a,0,n-1);

cout <<" numbers after sort";

for(i=0;i<n;i++)

cout << a[i] << " ";

getch();

void mergesort(int a[],int i,int j)

int mid;

if(i<j)

mid=(i+j)/2;

mergesort(a,i,mid);

mergesort(a,mid+1,j);

merge(a,i,mid,j);

void merge(int a[],int low,int mid ,int high)

int h,i,j,k;

h=low;

i=low;

j=mid+1;

while(h<=mid && j<=high)

if(a[h]<=a[j])

b[i]=a[h++];

else

b[i]=a[j++];

81 | P a g e
i++;

if( h > mid)

for(k=j;k<=high;k++)

b[i++]=a[k];

else

for(k=h;k<=mid;k++)

b[i++]=a[k];

cout <<"\n";

for(k=low;k<=high;k++)

{ a[k]=b[k];

cout << a[k] <<" ";

OUTPUT
N enter no of elements8 12 5 61 60 50 1 70 81
enter the elements
5 12
60 61
5 12 60 61
1 50
70 81
1 50 70 81
1 5 12 50 60 61 70 81
numbers after sort 1 5 12 50 60 61 70 81

82 | P a g e
12 /* Write a C++ program to implement all the functions of a dictionary (ADT) using
hashing */

#include<iostream>

#include<conio.h>

#include<stdlib.h>

using namespace std;

# define max 10

typedef struct list

int data;

struct list *next;

83 | P a g e
}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++)

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

84 | P a g e
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;

85 | P a g e
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];

while(temp[index]->data!=key && temp[index]!=NULL)

ptr[index]=temp[index];

temp[index]=temp[index]->next;

ptr[index]->next=temp[index]->next;

cout<<"\n"<<temp[index]->data<<" has been deleted.";

temp[index]->data=-1;

temp[index]=NULL;

free(temp[index]);

main()
{
int val,ch,n,num;
char c;
Dictionary d;
do
{
cout<<"\nMENU:\n1.Create";
cout<<"\n2.Search for a value\n3.Delete an value";
cout<<"\nEnter your choice:";

86 | P a g e
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter the number of elements to be inserted:";
cin>>n;
cout<<"\nEnter the elements to be inserted:";
for(int i=0;i<n;i++)
{
cin>>num;
d.insert(num);
}
break;
case 2:cout<<"\nEnter the element to be searched:";
cin>>n;
d.search(n);
case 3:cout<<"\nEnter the element to be deleted:";
cin>>n;
d.delete_ele(n);
break;
default:cout<<"\nInvalid choice....";
}
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:8

87 | P a g e
Enter the elements to be inserted:10 4 5 8 7 12 6 1

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:12

Search key is found!!


Enter the element to be deleted:1

1 has been deleted.


Enter y to continue......y

88 | P a g e
13. Write a C++ program that implements Radix sort algorithm for sorting a list of integers in
ascending order

#include <iostream>

using namespace std;

// Get maximum value from array.


int getMax(int arr[], int n)
{
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}

// Count sort of arr[].


void countSort(int arr[], int n, int exp)
{
// Count[i] array will be counting the number of array values having that 'i' digit at their (exp)th
place.
int output[n], i, count[10] = {0};

// Count the number of times each digit occurred at (exp)th place in every input.
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

// Calculating their cumulative count.


for (i = 1; i < 10; i++)
count[i] += count[i-1];

// Inserting values according to the digit '(arr[i] / exp) % 10' fetched into count[(arr[i] / exp) % 10].
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Assigning the result to the arr pointer of main().


for (i = 0; i < n; i++)
arr[i] = output[i];
}

// Sort arr[] of size n using Radix Sort.


void radixsort(int arr[], int n)
{
int exp, m;
m = getMax(arr, n);

// Calling countSort() for digit at (exp)th place in every input.


for (exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{

89 | P a g e
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

radixsort(arr, n);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}

Output
Enter the number of data element to be sorted: 10
Enter element 1: 886
Enter element 2: 542
Enter element 3: 12
Enter element 4: 3
Enter element 5: 96
Enter element 6: 1125
Enter element 7: 54
Enter element 8: 129
Enter element 9: 3125
Enter element 10: 1

Sorted Data ->1->3->12->54->96->129->542->886->1125->3125

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

a) AIM:Create a binary search tree of integers.


/*
* C++ Program to Implement Randomized Binary Search Tree
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdlib>
#define MAX_VALUE 65536
using namespace std;
/*
* Class RBSTNode
*/
class RBSTNode
{

90 | P a g e
public:
RBSTNode *left, *right;
int priority, element;
/* Constructor */
RBSTNode()
{
this->element = 0;
this->left = this;
this->right = this;
this->priority = MAX_VALUE;
}
/* Constructor */
RBSTNode(int ele)
{
RBSTNode(ele, NULL, NULL);
}
/* Constructor */
RBSTNode(int ele, RBSTNode *left, RBSTNode *right)
{
this->element = ele;
this->left = left;
this->right = right;
this->priority = rand() % 100 + 1;
}
};

/*
* Class RandomizedBinarySearchTree
*/
class RandomizedBinarySearchTree
{
private:
RBSTNode *root;
RBSTNode *nil;
public:
/* Constructor */
RandomizedBinarySearchTree()
{
root = nil;
}
/* Function to check if tree is empty */
bool isEmpty()
{
return root == nil;
}
/* Make the tree logically empty **/
void makeEmpty()
{
root = nil;
}

91 | P a g e
/* Functions to insert data **/
void insert(int X)
{
root = insert(X, root);
}
RBSTNode *insert(int X, RBSTNode *T)\
{
if (T == nil)
return new RBSTNode(X, nil, nil);
else if (X < T->element)
{
T->left = insert(X, T->left);
if (T->left->priority < T->priority)
{
RBSTNode *L = T->left;
T->left = L->right;
L->right = T;
return L;
}
}
else if (X > T->element)
{
T->right = insert(X, T->right);
if (T->right->priority < T->priority)
{
RBSTNode *R = T->right;
T->right = R->left;
R->left = T;
return R;
}
}
return T;
}
/*
* Functions to count number of nodes
*/
int countNodes()
{
return countNodes(root);
}

int countNodes(RBSTNode *r)


{
if (r == nil)
return 0;
else
{
int l = 1;
l += countNodes(r->left);

92 | P a g e
l += countNodes(r->right);
return l;
}
}
/*
* Functions to search for an element
*/
bool search(int val)
{
return search(root, val);
}
bool search(RBSTNode *r, int val)
{
bool found = false;
while ((r != nil) && !found)
{
int rval = r->element;
if (val < rval)
r = r->left;
else if (val > rval)
r = r->right;
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}

/*
* Function for inorder traversal
*/
void inorder()
{
inorder(root);
}

void inorder(RBSTNode *r)


{
if (r != nil)
{
inorder(r->left);
cout<<r->element <<" ";
inorder(r->right);
}
}
/*
* Function for preorder traversal

93 | P a g e
*/
void preorder()
{
preorder(root);
}
void preorder(RBSTNode *r)
{
if (r != nil)
{
cout<<r->element <<" ";
preorder(r->left);
preorder(r->right);
}
}

/*
* Function for postorder traversal
*/
void postorder()
{
postorder(root);
}
void postorder(RBSTNode *r)
{
if (r != nil)
{
postorder(r->left);
postorder(r->right);
cout<<r->element <<" ";
}
}
};

/*
* Main Contains Menu
*/

int main()
{
RandomizedBinarySearchTree rbst;
cout<<"Randomized Binary SearchTree Test\n";
char ch;
int choice, item;
/*
* Perform tree operations
*/
do
{
cout<<"\nRandomized Binary SearchTree Operations\n";
cout<<"1. Insert "<<endl;

94 | P a g e
cout<<"2. Search "<<endl;
cout<<"3. Count Nodes "<<endl;
cout<<"4. Check Empty"<<endl;
cout<<"5. Clear"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter integer element to insert: ";
cin>>item;
rbst.insert(item);
break;
case 2:
cout<<"Enter integer element to search: ";
cin>>item;
if (rbst.search(item))
cout<<"Element "<<item<<" found in the Tree"<<endl;
else
cout<<"Element "<<item<<" not found in the Tree"<<endl;
break;
case 3:
cout<<"Nodes = "<<rbst.countNodes()<<endl;
break;
case 4:
if (rbst.isEmpty())
cout<<"Tree is Empty"<<endl;
else
cout<<"Tree is not Empty"<<endl;
break;
case 5:
cout<<"\nRandomizedBinarySearchTree Cleared"<<endl;
rbst.makeEmpty();
break;
default:
cout<<"Wrong Entry \n ";
break;
}

/** Display tree **/


cout<<"\nPost order : ";
rbst.postorder();
cout<<"\nPre order : ";
rbst.preorder();
cout<<"\nIn order : ";
rbst.inorder();
cout<<"\nDo you want to continue (Type y or n) \n";
cin>>ch;
}
while (ch == 'Y'|| ch == 'y');

95 | P a g e
return 0;
}

/*Output
Randomized Binary SearchTree Test

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 28

Post order : 28
Pre order : 28
In order : 28
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 5

Post order : 5 28
Pre order : 28 5
In order : 5 28
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 63

Post order : 5 28 63
Pre order : 63 28 5
In order : 5 28 63
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 24

Post order : 5 28 63 24
Pre order : 24 5 63 28
In order : 5 24 28 63
Do you want to continue (Type y or n)
y

96 | P a g e
Randomized Binary SearchTree Operations
1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 64

Post order : 5 28 64 63 24
Pre order : 24 5 63 28 64
In order : 5 24 28 63 64
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 19

Post order : 5 19 28 64 63 24
Pre order : 24 19 5 63 28 64
In order : 5 19 24 28 63 64
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 1
Enter integer element to insert: 94

Post order : 5 19 28 94 64 63 24
Pre order : 24 19 5 63 28 64 94
In order : 5 19 24 28 63 64 94
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 2
Enter integer element to search: 24
Element 24 found in the Tree

Post order : 5 19 28 94 64 63 24
Pre order : 24 19 5 63 28 64 94
In order : 5 19 24 28 63 64 94
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search

97 | P a g e
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 2
Enter integer element to search: 25
Element 25 not found in the Tree

Post order : 5 19 28 94 64 63 24
Pre order : 24 19 5 63 28 64 94
In order : 5 19 24 28 63 64 94
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 3
Nodes = 7

Post order : 5 19 28 94 64 63 24
Pre order : 24 19 5 63 28 64 94
In order : 5 19 24 28 63 64 94
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 4
Tree is not Empty

Post order : 5 19 28 94 64 63 24
Pre order : 24 19 5 63 28 64 94
In order : 5 19 24 28 63 64 94
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear
Enter your choice: 5

RandomizedBinarySearchTree Cleared

Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
y

Randomized Binary SearchTree Operations


1. Insert
2. Search
3. Count Nodes
4. Check Empty
5. Clear

98 | P a g e
Enter your choice: 4
Tree is Empty

Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
n

------------------
(program exited with code: 1)
Press return to continue

*/

b).AIM: Traverse the above Binary search tree non recursively in inorder

#include<iostream>

#include<conio.h>

#include<stdlib.h>

using namespace std;

class node

public:

class node *left;

class node *right;

int data;

};

class tree: public node

public:

int stk[50],top;

node *root;

tree()

99 | P a g e
root=NULL;

top=0;

void insert(int ch)

node *temp,*temp1;

if(root== NULL)

root=new node;

root->data=ch;

root->left=NULL;

root->right=NULL;

return;

temp1=new node;

temp1->data=ch;

temp1->right=temp1->left=NULL;

temp=search(root,ch);

if(temp->data>ch)

temp->left=temp1;

else

temp->right=temp1;

node *search(node *temp,int ch)

100 |
Page
if(root== NULL)

cout <<"no node present";

return NULL;

if(temp->left==NULL && temp->right== NULL)

return temp;

if(temp->data>ch)

{ if(temp->left==NULL) return temp;

search(temp->left,ch);}

else

{ if(temp->right==NULL) return temp;

search(temp->right,ch);

void display(node *temp)

if(temp==NULL)

return ;

display(temp->left);

cout<<temp->data;

display(temp->right);

void inorder( node *root)

101 |
Page
{

node *p;

p=root;

top=0;

do

while(p!=NULL)

stk[top]=p->data;

top++;

p=p->left;

if(top>0)

p=pop(root);

cout << p->data;

p=p->right;

}while(top!=0 || p!=NULL);

node * pop(node *p)

int ch;

ch=stk[top-1];

if(p->data==ch)

102 |
Page
{

top--;

return p;

if(p->data>ch)

pop(p->left);

else

pop(p->right);

};

main()

tree t1;

int ch,n,i;

while(1)

cout <<"\n1.INSERT\n 2.DISPLAY 3.INORDER TRAVERSE\n 4.EXIT\n Enter your


choice:";

cin >> ch;

switch(ch)

case 1: cout <<"enter no of elements to insert:";

cin >> n;

for(i=1;i<=n;i++)

{ cin >> ch;

103 |
Page
t1.insert(ch);

break;

case 2: t1.display(t1.root);

break;

case 3: t1.inorder(t1.root);

break;

case 4: exit(1);

OUTPUT
1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:1
enter no of elements to inser
5 24 36 11 44 2 21

1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:3
251121243644
1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:3
251121243644
1.INSERT
2.DISPLAY 3.INORDER TRAVERSE
4.EXIT
Enter your choice:4

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

a) AIM:Create a binary search tree of integers.


#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;

void insert(int,int );
void delte(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)
{
cout <<"1.INSERT\n2.DELETE\n3.DISPLAY\n4.SEARCH\n5.EXIT\nEnter your choice:";
cin >> ch;
switch(ch)
{
case 1:
cout <<"enter the element to insert";
cin >> ch;
insert(1,ch);
break;
case 2:
cout <<"enter the element to delete";
cin >>x;
y=search(1);
if(y!=-1) delte(y);
else cout<<"no such element in tree";
break;
case 3:
display(1);
cout<<"\n";
for(int i=0;i<=32;i++)
cout <<i;
cout <<"\n";
break;
case 4:
cout <<"enter the element to search:";
cin >> x;
y=search(1);
if(y == -1) cout <<"no such element in tree";
else cout <<x << "is in" <<y <<"position";
break;
case 5:
exit(0);
}
}
}

105 |
Page
void insert(int s,int ch )
{
int x;
if(t==1)
{
tree[t++]=ch;
return;
}
x=search1(s,ch);
if(tree[x]>ch)
tree[2*x]=ch;
else
tree[2*x+1]=ch;
t++;
}
void delte(int x)
{
if( tree[2*x]==-1 && tree[2*x+1]==-1)
tree[x]=-1;
else if(tree[2*x]==-1)
{ tree[x]=tree[2*x+1];
tree[2*x+1]=-1;
}
else if(tree[2*x+1]==-1)
{ tree[x]=tree[2*x];
tree[2*x]=-1;
}
else
{
tree[x]=tree[2*x];
delte(2*x);
}
t--;
}

int search(int s)
{
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 ;
}

int search1(int s,int ch)

106 |
Page
{
if(t==1)
{
cout <<"no element in tree";
return -1;
}
if(tree[s]==-1)
return s/2;
if(tree[s] > ch)
search1(2*s,ch);
else search1(2*s+1,ch);
}

OUTPUT
1.INSERT
2.DELETE
3.DISPLAY
4.SEARCH
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

Enter the element to insert 10


1.INSERT
2.DELETE
3.DISPLAY
4.SEARCH
5.EXIT
Enter your choice:4

Enter the element to search: 10


10 is in 1 position
1.INSERT
2.DELETE
3.DISPLAY
4.SEARCH
5.EXIT

Enter your choice:5

107 |
Page
b) Search for an integer key in the above binary search tree non recursively.

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:
class node *left;
class node *right;
int data;
};

class tree: public node


{
public:
int stk[50], top;
node *root;
tree()
{
root = NULL;
top = 0;
}
void insert(int ch)
{
node *temp, *temp1;
if (root == NULL)
{
root = new node;
root->data = ch;
root->left = NULL;
root->right = NULL;
return;
}
temp1 = new node;
temp1->data = ch;
temp1->right = temp1->left = NULL;
temp = search(root, ch);
if (temp->data > ch)
temp->left = temp1;
else
temp->right = temp1;

node *search(node *temp, int ch)


{
if (root == NULL)
{

108 |
Page
cout << "no node present";
return NULL;
}
if (temp->left == NULL && temp->right == NULL)
return temp;

if (temp->data > ch)


{
if (temp->left == NULL)
return temp;
search(temp->left, ch);
}
else
{
if (temp->right == NULL)
return temp;
search(temp->right, ch);

}
}

void display(node *temp)


{
if (temp == NULL)
return;
display(temp->left);
cout << temp->data << " ";
display(temp->right);
}
void inorder(node *root)
{
node *p;
p = root;
top = 0;
do
{
while (p != NULL)
{
stk[top] = p->data;
top++;
p = p->left;
}
if (top > 0)
{
p = pop(root);
cout << p->data << " ";
p = p->right;
}
}
while (top != 0 || p != NULL);

109 |
Page
}

node * pop(node *p)


{
int ch;
ch = stk[top - 1];
if (p->data == ch)
{
top--;
return p;
}
if (p->data > ch)
pop(p->left);
else
pop(p->right);
}
};

int main(int argc, char **argv)


{
tree t1;
int ch, n, i;
while (1)
{
cout
<< "\n1.INSERT\n2.DISPLAY\n3.INORDER TRAVERSE\n4.EXIT\nEnter your choice:";
cin >> ch;
switch (ch)
{
case 1:
cout << "enter no of elements to insert:";
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> ch;
t1.insert(ch);
}
break;
case 2:
t1.display(t1.root);
break;
case 3:
t1.inorder(t1.root);
break;
case 4:
exit(1);
}
}
}

110 |
Page
Output:
1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:1
enter no of elements to insert:5
12 23 34 45 56

1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:3
12 23 34 45 56

1.INSERT
2.DISPLAY
3.INORDER TRAVERSE
4.EXIT
Enter your choice:4

------------------
(program exited with code: 0)
Press return to continue

c)AIM: Search for an integer key in the above binary search tree recursively.

/*
* C++ Program to Implement a Binary Search Tree using Linked Lists
*/
#include <iostream>
using namespace std;
#include <conio.h>
struct tree
{
tree *l, *r;
int data;
}*root = NULL, *p = NULL, *np = NULL, *q;

void create()
{
int value,c = 0;
while (c < 7)
{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}

111 |
Page
else
{
p = root;
cout<<"enter value of node\n";
cin>>value;
while(true)
{
if (value < p->data)
{
if (p->l == NULL)
{
p->l = new tree;
p = p->l;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
}
else if (p->l != NULL)
{
p = p->l;
}
}
else if (value > p->data)
{
if (p->r == NULL)
{
p->r = new tree;
p = p->r;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
}
else if (p->r != NULL)
{
p = p->r;
}
}
}
}
c++;
}
}
void inorder(tree *p)
{
if (p != NULL)
{

112 |
Page
inorder(p->l);
cout<<p->data<<endl;
inorder(p->r);
}
}
void preorder(tree *p)
{
if (p != NULL)
{
cout<<p->data<<endl;
preorder(p->l);
preorder(p->r);
}
}
void postorder(tree *p)
{
if (p != NULL)
{
postorder(p->l);
postorder(p->r);
cout<<p->data<<endl;
}
}
int main()
{
create();
cout<<"printing traversal in inorder\n";
inorder(root);
cout<<"printing traversal in preorder\n";
preorder(root);
cout<<"printing traversal in postorder\n";
postorder(root);
getch();
}
Output
enter value of root node
7
enter value of node
8
value entered in right
enter value of node
4
value entered in left
enter value of node
6
value entered in right
enter value of node
3
value entered in left
enter value of node
5
value entered in left
enter value of node
2
value entered in left

113 |
Page
printing traversal in inorder
2
3
4
5
6
7
8
printing traversal in preorder
7
4
3
2
6
5
8
printing traversal in postorder
2
3
5
6
4
8
7

114 |
Page
115 | P a g e

You might also like