DATA STRUCTURES (R18A0584)
LABORATORY MANUAL & RECORD
B.TECH (R18)
(II YEAR – I SEM) (2020-21)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Autonomous Institution – UGC, Govt. of India) Recognized under 2(f) and 12 (B) of UGC ACT 1956
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Vision
To acknowledge quality education and instill high patterns of discipline
making the students technologically superior and ethically strong which
involves the improvement in the quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of
infrastructure, outstanding technical and teaching expertise to establish
the students into competent and confident engineers.
Evolving the center of excellence through creative and innovative
teaching learning practices for promoting academic achievement to
produce internationally accepted competitive and world class
professionals.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
PEO1 – ANALYTICAL SKILLS
1. To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to
address the challenges of complex and computation intensive problems increasing
their productivity.
PEO2 – TECHNICAL SKILLS
2. To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the
technology in advanced areas of computer science and related fields, thus
encouraging to pursue higher education and research based on their interest.
PEO3 – SOFT SKILLS
3. To facilitate the graduates with the soft skills that include fulfilling the mission,
setting goals, showing self-confidence by communicating effectively, having a
positive attitude, get involved in team-work, being a leader, managing their career
and their life.
PEO4 – PROFESSIONAL ETHICS
To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety
codes,and adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
After the completion of the course, B. Tech Computer Science and Engineering, the
graduates will have the following Program Specific Outcomes:
1. Fundamentals and critical knowledge of the Computer System:- Able to Understand
the working principles of the computer System and its components , Apply the
knowledge to build, asses, and analyze the software and hardware aspects of it .
2. The comprehensive and Applicative knowledge of Software Development:
Comprehensive skills of Programming Languages, Software process models,
methodologies, and able to plan, develop, test, analyze, and manage the software
and hardware intensive systems in heterogeneous platforms individually or working
in teams.
3. Applications of Computing Domain & Research: Able to use the professional,
managerial, interdisciplinary skill set, and domain specific tools in development
processes, identify the research gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to: 1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and design system components or processes that meet the specified needs with appropriate consideration for the public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multi disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest context of technological change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions.Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.
Head of the Department Principal
Course Objectives and Course Outcomes Objectives: To write and execute programs in C++ to solve problems using data
structures such as arrays, linked lists, stacks, queues.
To write and execute programs in C++ to solve problems using data
structures such as trees, graphs, hash tables and search trees.
To write and execute write programs in C++ to implement various
sorting and searching methods.
Outcomes: Graduates will be able to identify the appropriate data structure for
given problem.
Graduate will be able to design programs for solving problems using
different data structures.
Gradualtes can solve problems using trees, graphs and hash tables
addressing various issues.
Graduates will have ability to effectively use compilers includes library
functions, debuggers and trouble shooting.
INDEX
S. No Topic Page no
1 Write a program that uses functions to perform the following operations on singly linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
1
2 Write a program that uses functions to perform the following operations on doubly linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
10
3 Write a program that uses functions to perform the following operations on circular linked List i) Creation ii) Insertion iii) Deletion iv) Traversal.
19
4 Write a program that implement stack (its operations) using i) Arrays ii) Linked list(Pointers).
26
5 Write a program that implement Queue (its operations) using i) Arrays ii) Linked list(Pointers).
35
6
i)Write a program that implement Circular Queue (its operations) using Arrays . ii) Write a program that uses both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers: a) Linear search b) Binary search.
42
7 Write a program that implements the following sorting i) Bubble sort ii) Selection sort iii)Quick sort.
52
8 Write a program that implements the following i) Insertion sort ii) Merge sort iii)Heap sort.
59
9 Write a program to implement all the functions of a dictionary (ADT)using Linked List.
67
10
Write a program to perform the following operations: a) Insert an element into a binary search tree. b) Delete an element from a binary search tree. c) Search for a key element in a binary search tree.
73
11 Write a program to implement the tree traversal methods. 82
12
Write a program to perform the following operations: a) Insert an element into a AVL tree. b) Delete an element from a AVL tree. c) Search for a key element in a AVL tree.
89
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 1
Aim: To write a C++ program to perform operations on singly linked list.
PROGRAM:
#include<iostream> #include<windows.h>
#include<conio.h>
using namespace std; class list
{
struct node
{ int data;
node *link;
}*p;
public:
void inslast(int);
void insbeg(int);
void insnext(int,int); void delelement(int);
void delbeg();
void dellast(); void disp();
int seek(int);
list(){p=NULL;}
~list(); };
void list::inslast(int x)
{ node *q,*t;
if(p==NULL)
{ p=new node;
p->data=x;
p->link=NULL;
} else
{
q=p; while(q->link!=NULL)
q=q->link;
t=new node; t->data=x;
t->link=NULL;
q->link=t;
} cout<<"Inserted successfully at the end..";
disp();
}
WEEK - 1
Write a program that uses functions to perform the following operations on singly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 2
void list:: insbeg(int x)
{
node *q; q=p;
p=new node;
p->data=x;
p->link=q; cout<<"Inserted successfully at the begining..";
disp();
}
void list::delelement(int x) {
node *q,*r;
q=p;
if(q->data==x) {
p=q->link;
delete q; return;
}
r=q; while(q!=NULL)
{
if(q->data==x)
{ r->link=q->link;
delete q;
return; }
r=q;
q=q->link;
} cout<<" Element u entered "<<x<<" is not found..";
}
void list:: delbeg() {
cout<<" The list before deletion:";
disp(); node *q;
q=p;
if(q==NULL)
{ cout<<" No data is present..";
return;
} p=q->link;
delete q;
return; }
void list:: dellast() {
cout<<" The list before deletion:";
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 3
disp();
node *q,*t;
q=p; if(q==NULL)
{
cout<<" There is no data in the list..";
return; }
if(q->link==NULL)
{ p=q->link;
delete q;
return; }
while(q->link->link!=NULL)
q=q->link; q->link=NULL;
return;
}
list::~list()
{ node *q;
if(p==NULL) return;
while(p!=NULL)
{ q=p->link;
delete p;
p=q; }
}
void list::disp() {
node *q;
q=p; if(q==NULL)
{
cout<<" No data is in the list.."; return;
}
cout<<" The items present in the list are :";
while(q!=NULL) {
cout<<" "<<q->data;
q=q->link; }
}
void list :: insnext(int value,int position)
{
node *temp,*temp1;
temp=p; if(temp1==NULL)
{
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 4
temp1= new node;
temp1->data=value;
temp1->link=NULL; p=temp1;
return;
}
for(int i=0;((i<position)&&(temp->link!=NULL)) ;i++) {
if(i==(position-1))
{ temp1= new node;
temp1->data= value;
temp1->link=temp->link; temp->link=temp1;
}
temp=temp->link;
} cout<<" Inserted successfully at the position.."<<position;
disp();
}
int list::seek(int value) {
node *temp;
temp=p;
int position=0; while(temp!=NULL)
{
if(temp->data==value) return position+1;
else
{
temp=temp->link; position=position+1;
}
} cout<<" Element "<<value<<" not found";
return 0;
}
int main()
{ list l;
int ch,v,p,ps;
do {
system("cls");
cout<<" Operations on List.."; cout<<"1.Insertion 2.Deletion 3.Display 4.Seek 5.Exit";
cout<<" Enter ur choice:";
cin>>ch;
switch(ch)
{
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 5
case 1:
cout<<"1.Insertion at begining\n2.Insertion at the end";
cout<<"3.Insertion after the mentioned position"; cout<<" Enter ur choice:";
cin>>ps;
cout<<" Enter the value to insert:";
cin>>v; switch(ps)
{
case 1: l.insbeg(v);
break;
case 2: l.inslast(v);
break;
case 3:
cout<<" Enter the position to insert the value:"; cin>>p;
l.insnext(v,p);
break;
default:
cout<<" The choice is invalid"; return 0;
}
break;
case 2:
cout<<"1.Delete the first element\n2.Delete the last element";
cout<<"\n3.Enter the element to delete from the list"; cout<<" \nEnter ur choice:";
cin>>ps;
switch(ps)
{ case 1:
l.delbeg();
cout<<" The list after deletion:"; l.disp();
break;
case 2: l.dellast();
cout<<" The list after deletion:";
l.disp();
break; case 3:
l.disp();
cout<<" Enter the element to delete : "; cin>>v;
l.delelement(v);
cout<<" The list after deletion:"; l.disp();
break;
default: cout<<" The option is invalid...";
break;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 6
}
break;
case 3:
l.disp();
break;
case 4:
l.disp();
cout<<" Enter the element to search:"; cin>>v;
cout<<" The position of the element "<< v<<" is "<<l.seek(v);
getch(); break;
case 5:
exit(1);
default:
cout<<" The option is invalid..."; return 0;
}
getch(); }while(ch!=5);
getch();
return 0;
}
Sample output
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 7
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 8
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 9
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 10
Aim: To write a C++ program to perform operations on doubly linked list.
Program:
#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()
{
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;
Week - 2
Write a program that uses functions to perform the following operations on doubly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 11
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; 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;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 12
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;
} }
/*
* 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)
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 13
{
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;
}
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)
{
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 14
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) {
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
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 15
*/
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; }
Sample Out:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 16
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 17
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 18
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 19
Aim: To write a C++ program to perform operations on circular linked list.
Program:
#include<iostream> #include<windows.h>
#include<conio.h>
using namespace std;
struct Node
{
int data; struct Node *next;
};
//insert a new node in an empty list struct Node *insertInEmpty(struct Node *last, int new_data)
{
// if last is not null then list is not empty, so return if (last != NULL)
return last;
// allocate memory for node struct Node *temp = new Node;
// Assign the data. temp -> data = new_data;
last = temp;
// Create the link. last->next = last;
return last; }
//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data) {
//if list is empty then add the node by calling insertInEmpty
if (last == NULL)
return insertInEmpty(last, new_data);
//else create a new node
struct Node *temp = new Node;
//set new data to node
temp -> data = new_data; temp -> next = last -> next;
last -> next = temp;
return last; }
//insert new node at the end of the list
Week - 3
Write a program that uses functions to perform the following operations on circular
linked List i) Creation ii) Insertion iii) Deletion iv) Traversal.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 20
struct Node *insertAtEnd(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty if (last == NULL)
return insertInEmpty(last, new_data);
//else create a new node struct Node *temp = new Node;
//assign data to new node temp -> data = new_data;
temp -> next = last -> next;
last -> next = temp; last = temp;
return last;
}
//insert a new node in between the nodes
struct Node *insertAfter(struct Node *last, int new_data, int after_item) {
//return null if list is empty
if (last == NULL) return NULL;
struct Node *temp, *p;
p = last -> next; do
{
if (p ->data == after_item) {
temp = new Node;
temp -> data = new_data;
temp -> next = p -> next; p -> next = temp;
if (p == last) last = temp;
return last;
} p = p -> next;
} while(p != last -> next);
cout << "The node with data "<<after_item << " is not present in the list." << endl; return last;
} //traverse the circular linked list
void traverseList(struct Node *last) {
struct Node *p;
// If list is empty, return.
if (last == NULL) {
cout << "Circular linked List is empty." << endl; return;
}
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 21
p = last -> next; // Point to the first Node in the list.
// Traverse the list starting from first node until first node is visited again
do {
cout << p -> data << "==>";
p = p -> next; } while(p != last->next);
if(p == last->next)
cout<<p->data; cout<<"\n\n";
}
//delete the node from the list
void deleteNode(Node** head, int key)
{
// If linked list is empty retun if (*head == NULL)
return;
// If the list contains only a single node,delete that node; list is empty
if((*head)->data==key && (*head)->next==*head) {
free(*head); *head=NULL;
}
Node *last=*head,*d;
// If key is the head
if((*head)->data==key) {
while(last->next!=*head) // Find the last node of the list last=last->next;
// point last node to next of head or second node of the list
last->next=(*head)->next; free(*head);
*head=last->next;
}
// end of list is reached or node to be deleted not there in the list
while(last->next!=*head&&last->next->data!=key) { last=last->next;
}
// node to be deleted is found, so free the memory and display the list
if(last->next->data==key) { d=last->next;
last->next=d->next;
cout<<"The node with data "<<key<<" deleted from the list"<<endl; free(d);
cout<<endl;
cout<<"Circular linked list after deleting "<<key<<" is as follows:"<<endl; traverseList(last);
}
else
cout<<"The node with data "<< key << " not found in the list"<<endl; }
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 22
// main Program
int main()
{ struct Node *last = NULL;
last = insertInEmpty(last, 30);
last = insertAtBegin(last, 20); last = insertAtBegin(last, 10);
last = insertAtEnd(last, 40);
last = insertAtEnd(last, 60); last = insertAfter(last, 50,40 );
cout<<"The circular linked list created is as follows:"<<endl;
traverseList(last); deleteNode(&last,10);
return 0;
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 23
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 24
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 25
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 26
Aim: To write a C++ program to implement stack operations using Arrays and Linked lists.
Program:
i) Using Arrays:
# include<iostream>
using namespace std; class Stack
{
int top;
public: int a[10]; //Maximum size of Stack
Stack()
{ top = -1;
}
// declaring all the function
void push(int x);
int pop();
void isEmpty(); void display();
};
//display stack contents void Stack::display()
{
int top1=top;
while(top1>-1) {
cout<<a[top1]<<"\n";
top1--; }
}
// function to insert data into stack void Stack::push(int x)
{
if(top >= 10)
{ cout << "Stack Overflow \n";
}
else {
a[++top] = x;
cout << "Element Inserted \n"; }
}
// function to remove data from the top of the stack int Stack::pop()
{
Week - 4
Write a program that implements stack (its operations) using i) Arrays ii) Linked list
(Pointers).
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 27
if(top < 0)
{
cout << "Stack Underflow \n"; return 0;
}
else
{ int d = a[top--];
return d;
} }
// function to check if stack is empty void Stack::isEmpty()
{
if(top < 0)
{ cout << "Stack is empty \n";
}
else {
cout << "Stack is not empty \n";
} }
// main function
int main() {
Stack s1;
int ch; int num;
while(1)
{
cout<<"1. Insert Element\n2. Delete Element\n3. Display Stack Elements\n4. Exit\nEnter
your option:";
cin>>ch;
switch(ch)
{ case 1:
cout<<"Enter Element to be inserted:";
cin>>num;
s1.push(num); break;
case 2:
cout<<"Element deleted from stack="<<s1.pop(); break;
case 3:
s1.display(); break;
case 4:
exit(0);
} }
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 28
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 29
ii) Using Linked List:
#include<iostream> #include<cstdlib>
using namespace std;
/* * Node Declaration
*/
struct node {
int info;
struct node *link; }*top;
/*
* Class Declaration */
class stack_list
{ public:
node *push(node *, int);
node *pop(node *); void traverse(node *);
stack_list()
{
top = NULL; }
};
/*
* Main: Contains Menu
*/
int main() {
int choice, item;
stack_list sl; while (1)
{
cout<<"\n-------------"<<endl; cout<<"Operations on Stack"<<endl;
cout<<"\n-------------"<<endl;
cout<<"1.Push Element into the Stack"<<endl;
cout<<"2.Pop Element from the Stack"<<endl; cout<<"3.Traverse the Stack"<<endl;
cout<<"4.Quit"<<endl;
cout<<"Enter your Choice: "; cin>>choice;
switch(choice)
{ case 1:
cout<<"Enter value to be pushed into the stack: ";
cin>>item;
top = sl.push(top, item); break;
case 2:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 30
top = sl.pop(top);
break;
case 3: sl.traverse(top);
break;
case 4:
exit(1); break;
default:
cout<<"Wrong Choice"<<endl; }
}
return 0; }
/*
* Push Element into the Stack */
node *stack_list::push(node *top, int item)
{ node *tmp;
tmp = new (struct node);
tmp->info = item; tmp->link = top;
top = tmp;
return top;
}
/*
* Pop Element from the Stack */
node *stack_list::pop(node *top)
{
node *tmp; if (top == NULL)
cout<<"Stack is Empty"<<endl;
else {
tmp = top;
cout<<"Element Popped: "<<tmp->info<<endl; top = top->link;
delete(tmp);
}
return top; }
/* * Traversing the Stack
*/
void stack_list::traverse(node *top) {
node *ptr;
ptr = top;
if (top == NULL) cout<<"Stack is empty"<<endl;
else
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 31
{
cout<<"Stack elements :"<<endl;
while (ptr != NULL) {
cout<<ptr->info<<endl;
ptr = ptr->link;
} }
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 32
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 33
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 34
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 35
Aim: To write a C++ program to implement Queue operations using Arrays and Linked lists.
Program:
i) Using Arrays:
#include <iostream>
using namespace std; int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1) cout<<"Queue Overflow"<<endl;
else {
if (front == - 1) front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val; rear++;
queue[rear] = val;
}
} void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow "; return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;; }
}
void Display() { if (front == - 1)
cout<<"Queue is empty"<<endl;
else { cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
cout<<endl; }
}
int main() { int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl; cin>>ch;
switch (ch) {
Week - 5
Write a program that implements Queue (its operations) using i) Arrays ii) Linked
list (Pointers).
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 36
case 1: Insert();
break;
case 2: Delete(); break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl; break;
default: cout<<"Invalid choice"<<endl;
} } while(ch!=4);
return 0;
}
Sample Output:
ii) Using Linked Lists:
#include <iostream>
#include<windows.h> using namespace std;
struct node {
int data;
struct node *next; };
struct node* front = NULL;
struct node* rear = NULL; struct node* temp;
void Insert() {
int val;
cout<<"Insert the element in queue : "<<endl; cin>>val;
if (rear == NULL) {
rear = (struct node *)malloc(sizeof(struct node));
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 37
rear->next = NULL;
rear->data = val;
front = rear; } else {
temp=(struct node *)malloc(sizeof(struct node));
rear->next = temp;
temp->data = val; temp->next = NULL;
rear = temp;
} }
void Delete() {
temp = front; if (front == NULL) {
cout<<"Underflow"<<endl;
return;
} else
if (temp->next != NULL) {
temp = temp->next; cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = temp; } else {
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = NULL; rear = NULL;
}
} void Display() {
temp = front;
if ((front == NULL) && (rear == NULL)) {
cout<<"Queue is empty"<<endl; return;
}
cout<<"Queue elements are: "; while (temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next; }
cout<<endl;
}
int main() { int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do { cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert(); break;
case 2: Delete();
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 38
break;
case 3: Display();
break; case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
} } while(ch!=4);
return 0;
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 39
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 40
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 41
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 42
Aim: To write a C++ program to implement Circular queues operations using Arrays.
Programs:
i) Circular Queue:
#include <iostream>
using namespace std; int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n"; return;
}
if (front == -1) {
front = 0; rear = 0;
} else {
if (rear == n - 1) rear = 0;
else
rear = rear + 1;
} cqueue[rear] = val ;
}
void deleteCQ() { if (front == -1) {
cout<<"Queue Underflow\n";
return ; }
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) { front = -1;
rear = -1;
} else { if (front == n - 1)
front = 0;
else front = front + 1;
}
}
void displayCQ() { int f = front, r = rear;
if (front == -1) {
Week - 6
i)Write a program that implement Circular Queue (its operations) using Arrays .
ii) Write a program that uses both recursive and non recursive functions to
perform the following searching operations for a Key value in a given list of
integers:
a) Linear search b) Binary search
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 43
cout<<"Queue is empty"<<endl;
return;
} cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" "; f++;
}
} else { while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++; }
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" "; f++;
}
} cout<<endl;
}
int main() {
int ch, val;
cout<<"1)Insert\n";
cout<<"2)Delete\n"; cout<<"3)Display\n";
cout<<"4)Exit\n";
do { cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1: cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val); break;
case 2: deleteCQ();
break;
case 3: displayCQ();
break;
case 4:
cout<<"Exit\n";
break; default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0; }
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 44
Sample Output:
ii) Linear search using non recursive function:
Aim: To write a C++ program to perform Linear Search using non-recursive function.
Program:
#include<iostream> using namespace std;
int Lsearch(int list[ ],int n,int key);
int main() {
int n,i,key,list[25],pos;
cout<<"enter no of elements\n";
cin>>n; cout<<"enter "<<n<<" elements ";
for(i=0;i<n;i++)
cin>>list[i]; cout<<"enter key to search";
cin>>key;
pos= Lsearch (list,n,key); if(pos==-1)
cout<<"\nelement not found";
else
cout<<"\n element found at index "<<pos; }
/*function for linear search*/
int Lsearch(int list[],int n,int key) {
int i,pos=-1;
for(i=0;i<n;i++)
if(key==list[i]) {
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 45
pos=i;
break;
} return pos;
}
Sample Output:
Linear search using recursive function:
Aim: To write a C++ program to perform Linear Search using recursive function.
Program:
#include<iostream>
using namespace std;
int Rec_Lsearch(int list[ ],int n,int key); int main()
{
int n,i,key,list[25],pos; cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" elements ";
for(i=0;i<n;i++) cin>>list[i];
cout<<"enter key to search";
cin>>key; pos=Rec_Lsearch(list,n,key);
if(pos==-1)
cout<<"\nelement not found";
else cout<<"\n element found at index "<<pos;
}
/*recursive function for linear search*/ int Rec_Lsearch(int list[],int n,int key)
{
if(n<=0) return -1;
if(list[n]==key)
return n;
else return Rec_Lsearch(list,n-1,key);
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 46
}
Sample Output:
Binary Search using non recursive function:
Aim: To write a C++ program to perform Binary Search using non-recursive function.
Program:
#include<iostream>
using namespace std;
int binary_search(int list[],int key,int low,int high); int main()
{
int n,i,key,list[25],pos; cout<<"enter no of elements\n" ;
cin>>n;
cout<<"enter "<<n<<" elements in ascending order ";
for(i=0;i<n;i++) cin>>list[i];
cout<<"enter key to search" ;
cin>>key; pos=binary_search(list,key,0,n-1);
if(pos==-1)
cout<<"element not found" ;
else cout<<"element found at index "<<pos;
}
/* function for binary search*/ int binary_search(int list[],int key,int low,int high)
{
int mid,pos=-1; while(low<=high)
{
mid=(low+high)/2;
if(key==list[mid]) {
pos=mid;
break;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 47
}
else if(key<list[mid])
high=mid-1; else
low=mid+1;
}
return pos; }
Sample Output:
Binary Search using recursive function:
Aim: To write a C++ program to perform Binary Search using recursive function.
Program:
#include<iostream>
using namespace std;
int rbinary_search(int list[],int key,int low,int high); int main()
{
int n,i,key,list[25],pos; cout<<"enter no of elements\n" ;
cin>>n;
cout<<"enter "<<n<<" elements in ascending order "; for(i=0;i<n;i++)
cin>>list[i];
cout<<"enter key to search" ;
cin>>key; pos=rbinary_search(list,key,0,n-1);
if(pos==-1)
cout<<"element not found" ; else
cout<<"element found at index "<<pos;
}
/*recursive function for binary search*/ int rbinary_search(int list[ ],int key,int low,int high)
{
int mid,pos=-1; if(low<=high)
{
mid=(low+high)/2;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 48
if(key==list[mid])
{
pos=mid; return pos;
}
else if(key<list[mid])
return rbinary_search(list,key,low,mid-1); else
return rbinary_search(list,key,mid+1,high);
} return pos;
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 49
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 50
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 51
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 52
i) Bubble Sort:
Aim: To write a C++ program to implement Bubble Sort.
Program:
#include<iostream> using namespace std;
void bubble_sort(int list[30],int n);
int main()
{ int n,i;
int list[30];
cout<<"enter no of elements\n"; cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++) cin>>list[i];
bubble_sort (list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++) cout<<list[i]<<endl;
return 0;
} void bubble_sort (int list[30],int n)
{
int temp ;
int i,j; for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(list[j]>list[j+1]) {
temp=list[j];
list[j]=list[j+1]; list[j+1]=temp;
}
}
Week - 7
Write a program that implements the following sorting
i) Bubble sort ii) Selection sort iii) Quick sort.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 53
Sample output:
ii) Selection Sort:
Aim: To write a C++ program to implement Selection Sort.
Program:
#include<iostream>
using namespace std; void selection_sort (int list[],int n);
int main()
{ int n,i;
int list[30];
cout<<"enter no of elements\n"; cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i]; selection_sort (list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++) cout<<list[i]<<endl;
return 0;
} void selection_sort (int list[],int n)
{
int min,temp,i,j;
for(i=0;i<n;i++) {
min=i;
for(j=i+1;j<n;j++) {
if(list[j]<list[min])
min=j;
} temp=list[i];
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 54
list[i]=list[min];
list[min]=temp;
} }
Sample output:
iii) Quick Sort:
Aim: To write a C++ program to implement Quick Sort.
Program:
#include<iostream>
using namespace std;
void quicksort(int x[],int Lb,int Ub) {
int down,up,pivot,t;
if(Lb<Ub) {
down=Lb;
up=Ub; pivot=down;
while(down<up)
{
while((x[down]<=x[pivot])&&(down<Ub))down++; while(x[up]>x[pivot])up--;
if(down<up)
{ t=x[down];
x[down]=x[up];
x[up]=t;
}/*endif*/ }
t=x[pivot];
x[pivot]=x[up]; x[up]=t;
quicksort( x,Lb,up-1);
quicksort( x,up+1,Ub); }
}
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 55
int main()
{
int n,i; int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers "; for(i=0;i<n;i++)
cin>>list[i];
quicksort(list,0,n-1); cout<<" after sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl; return 0;
}
Sample output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 56
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 57
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 58
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 59
i) Insertion Sort:
Aim: To write a C++ program to implement Insertion Sort.
Program:
#include<iostream>
using namespace std; void insertion_sort(int a[],int n)
{
int i,t,pos;
for(i=0;i<n;i++) {
t=a[i];
pos=i; while(pos>0&&a[pos-1]>t)
{
a[pos]=a[pos-1]; pos--;
}
a[pos]=t;
} }
int main()
{ int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n; cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i]; insertion_sort(list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++) cout<<list[i]<<endl;
return 0;
}
Sample Output:
Week - 8
Write a program that implements the following
i) Insertion sort ii) Merge sort iii) Heap sort
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 60
ii) Merge Sort:
Aim: To write a C++ program to implement Merge Sort.
Program:
#include<iostream>
using namespace std; void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a; a = b;
b = temp;
} void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl; }
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr; //size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++) rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++; }else{
array[k] = rarr[j];
j++;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 61
}
k++;
} while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
} while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++; }
}
void mergeSort(int *array, int l, int r) { int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r); }
}
int main() { int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i]; }
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index cout << "Array after Sorting: ";
display(arr, n);
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 62
iii) Heap Sort:
Aim: To write a C++ program to implement Heap Sort.
Program:
#include <iostream> using namespace std;
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest]) largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest]) largest = r;
// If largest is not root
if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest); }
}
// main function to do heap sort void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--) {
// Move current root to end
swap(arr[0], arr[i]); // call max heapify on the reduced heap
heapify(arr, i, 0);
}
} /* A utility function to print array of size n */
void printArray(int arr[], int n)
{ for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n"; }
int main()
{
int n,i; int list[30];
cout<<"enter no of elements\n";
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 63
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++) cin>>list[i];
heapSort(list, n);
cout << "Sorted array is \n";
printArray(list, n); return 0;
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 64
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 65
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 66
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 67
Aim: To write a C++ program to implement functions of Dictionary ADT using Linked List.
Program:
#include<stdlib.h> #include<iostream>
using namespace std;
class node {
public: int key;
int value;
node*next; };
class dictionary:public node
{ int k,data; node *head;
public: dictionary();
void insert_d(); void delete_d();
void display_d();
};
dictionary::dictionary() { head=NULL;
}
//code to push an val into dictionary; void dictionary::insert_d()
{
node *p,*curr,*prev;
cout<<"Enter an key and value to be inserted:"; cin>>k;
cin>>data;
p=new node; p->key=k;
p->value=data;
p->next=NULL; if(head==NULL)
head=p;
else
{ curr=head;
while((curr->key<p->key)&&(curr->next!=NULL))
{ prev=curr; curr=curr->next;
}
if(curr->next==NULL) {
if(curr->key<p->key)
{ curr->next=p;
prev=curr; }
else { p->next=prev->next;
Week - 9
Write a program to implement all the functions of a dictionary (ADT)using Linked
List.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 68
prev->next=p;
}
} else
{
p->next=prev->next;
prev->next=p; }
cout<<"\nInserted into dictionary Sucesfully....\n";
} }
void dictionary::delete_d( )
{ node*curr,*prev;
cout<<"Enter key value that you want to delete...";
cin>>k;
if(head==NULL) cout<<"\ndictionary is Underflow";
else
{ curr=head; while(curr!=NULL)
{
if(curr->key==k) break;
prev=curr;
curr=curr->next;
} }
if(curr==NULL)
cout<<"Node not found..."; else
{
if(curr==head)
head=curr->next; else
prev->next=curr->next;
delete curr; cout<<"Item deleted from dictionary...";
}
} void dictionary::display_d( )
{
node*t;
if(head==NULL) cout<<"\ndictionary Under Flow";
else
{ cout<<"\nElements in the dictionary are....\n";
t=head;
while(t!=NULL) {
cout<<"<"<<t->key<<","<<t->value<<">";
t=t->next;
} }
}
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 69
int main( )
{
int choice; dictionary d1;
while(1)
{
cout<<"\n\n***Menu for Dictrionay operations***\n\n"; cout<<"1.Insert\n2.Delete\n3.DISPLAY\n4.EXIT\n";
cout<<"Enter Choice:";
cin>>choice; switch(choice)
{
case 1: d1.insert_d(); break;
case 2: d1.delete_d( );
break;
case 3: d1.display_d( ); break;
case 4: exit(0);
default:cout<<"Invalid choice...Try again...\n"; }
}
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 70
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 71
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 72
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 73
Aim: To write a C++ program to perform insert, delete and search operations on Binary Search
Tree.
Program:
# include <iostream>
# include <cstdlib>
using namespace std; struct nod//node declaration
{
int info; struct nod *l;
struct nod *r;
}*r; class BST
{
public://functions declaration
void search(nod *, int); void insert(nod *, nod *);
void del(int);
void casea(nod *,nod *); void caseb(nod *,nod *);
void casec(nod *,nod *);
void find(int, nod **, nod **);
void show(nod *, int); BST()
{
r = NULL; }
};
void BST::casea(nod *par, nod *loc ) {
if (par == NULL)
{
r= NULL; }
else
{ if (loc == par->l)
par->l = NULL;
else par->r = NULL;
}
}
void BST::caseb(nod *par, nod *loc) {
nod *child;
Week - 10
Write a program to perform the following operations:
a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 74
if (loc->l!= NULL)
child = loc->l;
else child = loc->r;
if (par == NULL)
{
r = child; }
else
{ if (loc == par->l)
par->l = child;
else par->r = child;
}
}
void BST::casec(nod *par, nod *loc) {
nod *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc; ptr = loc->r;
while (ptr->l!= NULL)
{ ptrsave = ptr;
ptr = ptr->l;
}
suc = ptr; parsuc = ptrsave;
if (suc->l == NULL && suc->r == NULL)
casea(parsuc, suc); else
caseb(parsuc, suc);
if (par == NULL)
{ r = suc;
}
else {
if (loc == par->l)
par->l = suc; else
par->r= suc;
}
suc->l = loc->l; suc->r= loc->r;
}
void BST::search(nod *root, int data) //searching {
int depth = 0;
nod *temp = new nod; temp = root;
while(temp != NULL)
{
depth++; if(temp->info == data)
{
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 75
cout<<"\nData found at depth: "<<depth<<endl;
return;
} else if(temp->info > data)
temp = temp->l;
else
temp = temp->r; }
cout<<"\n Data not found"<<endl;
return; }
void BST::insert(nod *tree, nod *newnode)
{ if (r == NULL)
{
r = new nod;
r->info = newnode->info; r->l= NULL;
r->r= 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->l != NULL) {
insert(tree->l, newnode);
}
else {
tree->l= newnode;
(tree->l)->l = NULL; (tree->l)->r= NULL;
cout<<"Node Added To Left"<<endl;
return; }
}
else
{ if (tree->r != NULL)
{
insert(tree->r, newnode); }
else
{ tree->r = newnode;
(tree->r)->l= NULL;
(tree->r)->r = NULL;
cout<<"Node Added To Right"<<endl; return;
}
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 76
}
}
void BST::find(int i, nod **par, nod **loc)//find the position of the item {
nod *ptr, *ptrsave;
if (r == NULL)
{ *loc = NULL;
*par = NULL;
return; }
if (i == r->info)
{ *loc = r;
*par = NULL;
return;
} if (i < r->info)
ptr = r->l;
else ptr = r->r;
ptrsave = r;
while (ptr != NULL) {
if (i == ptr->info)
{
*loc = ptr; *par = ptrsave;
return;
} ptrsave = ptr;
if (i < ptr->info)
ptr = ptr->l;
else ptr = ptr->r;
}
*loc = NULL; *par = ptrsave;
}
void BST::del(int i) {
nod *par, *loc;
if (r == NULL)
{ cout<<"Tree empty"<<endl;
return;
} find(i, &par, &loc);
if (loc == NULL)
{ cout<<"Item not present in tree"<<endl;
return;
}
if (loc->l == NULL && loc->r == NULL) {
casea(par, loc);
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 77
cout<<"item deleted"<<endl;
}
if (loc->l!= NULL && loc->r == NULL) {
caseb(par, loc);
cout<<"item deleted"<<endl;
} if (loc->l== NULL && loc->r != NULL)
{
caseb(par, loc); cout<<"item deleted"<<endl;
}
if (loc->l != NULL && loc->r != NULL) {
casec(par, loc);
cout<<"item deleted"<<endl;
} free(loc);
}
void BST::show(nod *ptr, int level)//print the tree {
int i;
if (ptr != NULL) {
show(ptr->r, level+1);
cout<<endl;
if (ptr == r) cout<<"Root->: ";
else
{ for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info; show(ptr->l, level+1);
}
} int main()
{
int c, n,item; BST bst;
nod *t;
while (1)
{ cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Search Element"<<endl; cout<<"4.Display the tree"<<endl;
cout<<"5.Quit"<<endl;
cout<<"Enter your choice : "; cin>>c;
switch(c)
{
case 1: t = new nod;
cout<<"Enter the number to be inserted : ";
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 78
cin>>t->info;
bst.insert(r, t);
break; case 2:
if (r == NULL)
{
cout<<"Tree is empty, nothing to delete"<<endl; continue;
}
cout<<"Enter the number to be deleted : "; cin>>n;
bst.del(n);
break; case 3:
cout<<"Search:"<<endl;
cin>>item;
bst.search(r,item); break;
case 4:
cout<<"Display BST:"<<endl; bst.show(r,1);
cout<<endl;
break; case 5:
exit(1);
default:
cout<<"Wrong choice"<<endl; }
}
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 79
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 80
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 81
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 82
Aim: To write a C++ program to implement tree traversal methods..
Program:
# include <iostream> # include <cstdlib>
using namespace std;
struct nod//node declaration {
int info;
struct nod *l;
struct nod *r; }*r;
class BST
{ public://functions declaration
void insert(nod *, nod *);
void preorder(nod *); void inorder(nod *);
void postorder(nod *);
void show(nod *, int);
BST() {
r = NULL;
} };
void BST::insert(nod *tree, nod *newnode)
{
if (r == NULL) {
r = new nod;
r->info = newnode->info; r->l= NULL;
r->r= 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->l != NULL) {
insert(tree->l, newnode);
}
else {
tree->l= newnode;
Week - 11
Write a program to implement the tree traversal methods.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 83
(tree->l)->l = NULL;
(tree->l)->r= NULL;
cout<<"Node Added To Left"<<endl; return;
}
}
else {
if (tree->r != NULL)
{ insert(tree->r, newnode);
}
else {
tree->r = newnode;
(tree->r)->l= NULL;
(tree->r)->r = NULL; cout<<"Node Added To Right"<<endl;
return;
} }
}
void BST::preorder(nod *ptr) {
if (r == NULL)
{
cout<<"Tree is empty"<<endl; return;
}
if (ptr != NULL) {
cout<<ptr->info<<" ";
preorder(ptr->l);
preorder(ptr->r); }
}
void BST::inorder(nod *ptr)//inorder traversal {
if (r == NULL)
{ cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL) {
inorder(ptr->l);
cout<<ptr->info<<" "; inorder(ptr->r);
}
} void BST::postorder(nod *ptr)//postorder traversal
{
if (r == NULL)
{ cout<<"Tree is empty"<<endl;
return;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 84
}
if (ptr != NULL)
{ postorder(ptr->l);
postorder(ptr->r);
cout<<ptr->info<<" ";
} }
void BST::show(nod *ptr, int level)//print the tree
{ int i;
if (ptr != NULL)
{ show(ptr->r, level+1);
cout<<endl;
if (ptr == r)
cout<<"Root->: "; else
{
for (i = 0;i < level;i++) cout<<" ";
}
cout<<ptr->info; show(ptr->l, level+1);
}
}
int main() {
int c, n,item;
BST bst; nod *t;
while (1)
{
cout<<"1.Insert Element "<<endl; cout<<"2.Inorder Traversal"<<endl;
cout<<"3.Preorder Traversal"<<endl;
cout<<"4.Postorder Traversal"<<endl; cout<<"5.Display the tree"<<endl;
cout<<"6.Quit"<<endl;
cout<<"Enter your choice : "; cin>>c;
switch(c)
{
case 1: t = new nod;
cout<<"Enter the number to be inserted : ";
cin>>t->info; bst.insert(r, t);
break;
case 2: cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(r);
cout<<endl;
break; case 3:
cout<<"Preorder Traversal of BST:"<<endl;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 85
bst.preorder(r);
cout<<endl;
break; case 4:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(r);
cout<<endl; break;
case 5:
cout<<"Display BST:"<<endl; bst.show(r,1);
cout<<endl;
break; case 6:
exit(1);
default:
cout<<"Wrong choice"<<endl; }
}
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 86
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 87
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 88
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 89
Aim: To write a C++ program to perform insert, delete and search operations on AVL tree.
Program:
# include <iostream>
# include <stdlib.h>
# include <conio.h>
using namespace std; struct node
{
int element; node *left;
node *right;
int height; };
typedef struct node *np;
class bstree
{ public:
void insert(int,np &);
void del(int, np &); int deletemin(np &);
void find(int,np &);
int bsheight(np);
np srl(np &); np drl(np &);
np srr(np &);
np drr(np &); };
int bstree::deletemin(np &p)
{ int c;
cout<<"inside deltemin";
if (p->left == NULL)
{ c=p->element;
p=p->right;
return c; }
else
{ c=deletemin(p->left);
return c;
}
} int bstree::bsheight(np p)
{
Week - 12
Write a program to perform the following operations:
a) Insert an element into an AVL tree.
b) Delete an element from an AVL tree.
c) Search for a key element in an AVL tree.
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 90
int t;
if (p == NULL)
return -1; else
{
t = p->height;
return t; }
}
np bstree:: srl(np &p1) {
np p2;
p2 = p1->left; p1->left = p2->right;
p2->right = p1;
p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;
p2->height = max(bsheight(p2->left),p1->height) + 1; return p2;
}
np bstree:: srr(np &p1) {
np p2;
p2 = p1->right; p1->right = p2->left;
p2->left = p1;
p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;
p2->height = max(p1->height,bsheight(p2->right)) + 1; return p2;
}
np bstree:: drl(np &p1) {
p1->left=srr(p1->left);
return srl(p1);
} np bstree::drr(np &p1)
{
p1->right = srl(p1->right); return srr(p1);
}
// Inserting a node void bstree::insert(int x,np &p)
{
if (p == NULL)
{ p = new node;
p->element = x;
p->left=NULL; p->right = NULL;
p->height=0;
if (p==NULL) cout<<"Out of Space";
}
else
{ if (x<p->element)
{
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 91
insert(x,p->left);
if ((bsheight(p->left) - bsheight(p->right))==2)
{ if (x < p->left->element)
p=srl(p);
else
p = drl(p); }
}
else if (x>p->element) {
insert(x,p->right);
if ((bsheight(p->right) - bsheight(p->left))==2) {
if (x > p->right->element)
p=srr(p);
else p = drr(p);
}
} else
cout<<"Element Exists";
} int m,n,d;
m=bsheight(p->left);
n=bsheight(p->right);
d=max(m,n); p->height = d + 1;
}
// Deleting a node void bstree::del(int x,np &p)
{
np d;
if (p==NULL) cout<<"Element not found ";
else if ( x < p->element)
del(x,p->left); else if (x > p->element)
del(x,p->right);
else if ((p->left == NULL) && (p->right == NULL)) {
d=p;
free(d);
p=NULL; cout<<" Element deleted !";
}
else if (p->left == NULL) {
d=p;
free(d); p=p->right;
cout<<" Element deleted !";
}
else if (p->right == NULL) {
d=p;
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 92
p=p->left;
free(d);
cout<<" Element deleted !"; }
else
p->element = deletemin(p->right);
} //Finding an element
void bstree::find(int x,np &p)
{ if (p==NULL)
cout<<" Element not found ";
else if (x < p->element)
find(x,p->left);
else
if (x>p->element) find(x,p->right);
else
cout<<" Element found !"; }
int main()
{ //clrscr();
np root,root1,min,max;//,flag;
int a,choice,findele,delele,leftele,rightele,flag;
char ch='y'; bstree bst;
//system("clear");
root = NULL; root1=NULL;
while(1)
{
cout<<" \nAVL Tree\n"; cout<<" ========\n";
cout<<"1.Insertion\n2.Find\n3.Delete\n4.Exit\n";
cout<<"Enter the choice:"; cin>>choice;
switch(choice)
{ case 1:
cout<<"New node's value ?";
cin>>a;
bst.insert(a,root); break;
case 2:
cout<<"Search node : "; cin>>findele;
if (root != NULL)
bst.find(findele,root); break;
case 3:
cout<<"Delete Node ?";
cin>>delele; bst.del(delele,root);
//bst.inorder(root);
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 93
break;
case 4:exit(0);
} }
return 0;
}
Sample Output:
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 94
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 95
Record Notes
Data Structures Lab Manual & Record MRCET
Department of Computer Science and Engineering 96
Record Notes