Vous êtes sur la page 1sur 84

# Data Structures Through C++ Lab LAB MANUAL

## vidya vikas Institute of technology

1
1. Write C++programs to implement the following using an array.
a) Stack ADT
b) Queue ADT

2. Write C++programs to implement the following using a singly linked list.
a) Stack ADT
b) Queue ADT
3. Write C++program to implement the deque (double ended queue) ADT using
a doubly linked list.
4. Write a C++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.
5. Write a C++program to implement circular queue ADT using an array.
6. Write C++programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.
7. Write a C++programs for the implementation of bfs and dfs for a given graph.
8. Write C++programs for implementing the following sorting methods:
a) Quick sort
b) Merge sort
c) Heap sort
9. Write a C++program to perform the following operations
a) Insertion into a B-tree
b) Deletion from a B-tree
10. Write a C++program to perform the following operations
a) Insertion into an AVL-tree
b) Deletion from an AVL-tree
11. Write a C++program to implement Kruskals algorithm to generate a minimum
spanning tree.
12. Write a C++program to implement Prims algorithm to generate a minimum
spanning tree.
13. Write a C++program to implement all the functions of a dictionary (ADT) using
hashing.
Templates
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
2
Template Functions
Suppose we want to write a function that finds the maximum of two objects. To find the
maximum of two integers we wouldwrite:
int maximal(int a, int b)
{
if (a >b)
return a;
else
return b;
}
and to find the maximum of two doubles we would write:
double maximal(double a, double b)
{
if (a >b)
return a;
else
return b;
}
and so on. You can imagine that we would have to write a separate function for every
data type (chars, strings, dates, etc.), but notice that the body of each function is exactly
the same!!!
Template Function Definition
The definition of a template function depends on an underlying data type.
For example:
template <class Item>
Item maximal(Item a, Item b)
{
if (a >b)
return a;
else
return b;
}
The first line is the template prefix, which tells the compiler that Itemis a data type that
will be filled in later. The "unspecified type" Itemis called the template parameter.
When a template function is called, the compiler examines the types of the arguments
and at that point determines the data type of Item.
Using Template Functions
Template functions are used (called) in exactly the same way as regular functions. For
example, if we want to output the maximum of the integers 1000 and 2000, we would
write:
cout <<maximal(1000, 2000) <<endl; // will print 2000
The maximal function is said to be instantiated with the data type Itemset to int.
Similarly, we could do:
cout <<maximal('a', 'z') <<endl; // will print 'z'
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
3
string s1("foo");
string s2("bar");
cout <<maximal(s1, s2) <<endl; // will print "foo"
Template Classes
A template class is a class that depends on an underlying data type in the same way a
template function depend on an underlying data type.
Template Class Definition
template <class Item>
class Bag
{
...
};
Functions for the Template Class
All member functions of a template class are dependent upon the Itemtype. Within the
template class definition, the compiler knows about this dependency. Outside the
template class definition (after the semicolon of the definition) some rules must be
followed to tell the compiler about the dependency on the Itemdata type:
The template prefix template <class Item>is placed immediately before each function
prototype and implementation, for example:
template <class Item>
void Bag<Item>::insert(const Item& entry);
Each use of the class name (such as Bag) as the name of a class is changed to the
template class name (such as Bag<Item>), for example:
template <class Item>
Bag<Item>::Bag(size_t initial_capacity);
Each use of the complete underlying type name (such as Bag item) may now be
shortened to just the type name (such as Item), for example
ItemBag<Item>::grab() const;
Usage
To declare a Bag, you write the class name followed by the name of the data type for
the template parameter. For example:
Bag<char>letters; //template parameter is instantiated to char
Bag<double>scores; //template parameter is instantiated to double
Another example :
List <int>list;
list.insert(10); // insert node containing integer 10
STACKS AND QUEUES
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
4
One of the most common forms of data organization in computer programs is the
ordered or linear list, which is often written as a =(a
1
, a
2
, .., a
n
). A stack is an ordered
list in which all insertions and deletions are made at one end, called the top. A queue is
an ordered list in which all insertions take place at one end, the rear, whereas all
deletions take place at the other end, the front.
The operations of a stack imply that if the elements A, B, C, D and E are inserted into a
stack, in that order, then the first element to be removed must be E. Equivalently we say
that the last element to be inserted into the stack is the first to be removed. For this
reason stacks are sometimes referred to as Last In First Out (LIFO) lists. The operations
of a queue require that the first element that is inserted into the queue is the first one to
be removed. Thus queues are known as First In First Out (FIFO) lists.
Stack Queue
Above figure shows the examples of a stack and queue each containing the same five
elements inserted in the sameorder.
The simplest way to represent a stack is by using a one-dimensional array, say stack[0 :
n-1], where n is the maximum number of allowable entries. The first or bottom element
in the stack is stored at stack, the second at stack, and ith at stack[i-1]. Associated
with the array is a variable, typically called top, which points to the top element, to test
whether the stack is empty, we ask if (top<0). If not, the topmost element is at
stack[top]. Checking whether the stack is full can be done by asking if (top n-1).
Two more substantial operations are inserting and deleting elements. The corresponding
algorithms are Add and Delete.
1. Write C++ programs to implement the following using an array.
a) Stack ADT
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define max 100
template <class T>
class stack
{
T x;
int top;
rear front
top
E
D
C
B
A
A B C D E
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
5
public:
stack();
void push(T);
T pop();
void display();
};
template <class T>
stack<T>::stack()
{
top=-1;
}
template <class T>
void stack<T>::push(T n)
{
if(top==max-1)
cout<<"stack is overflow"<<endl;
else
x[++top]=n;
}
template <class T>
T stack<T>::pop()
{
if(top==-1)
{
cout<<"stack is empty"<<endl;
return 0;
}
else
return x[top--];
}
template <class T>
void stack<T>::display()
{
int i;
if(top==-1)
cout<<"stack is empty"<<endl;
else
{
cout<<"\nStack Elements are"<<endl;
for(i=top;i>=0;i--)
cout<<x[i]<<endl;
}
}
void main()
{
stack<int>obj;
int ch,n;
clrscr();
do
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
6
{
cout<<"1.Push \n 2.Pop \n 3.Display \n 4.exit"<<endl;
cout<<"enter your choice"<<endl;
cin>>ch;
switch(ch)
{
case 1: cout<<"enter element to push to the stack"<<endl;
cin>>n;
obj.push(n);
break;
case 2:cout<<"poped element is"<<obj.pop();
case 3:obj.display();
break;
case 4:exit(0);
default: cout<<"invalid choice";
}
}while(1);
}
Queue ADT
AbstractDataType queue
{
instances
ordered list of elements; one end is called the front; the other is the back;
operations
empty( ) : return true if the queue is empty, return false otherwise;
size( ) : return the number of elements in the queue
front ( ) : return the front element of the queue
back( ) : return the back element of the queue
pop( ) : remove the top element from the queue
push(x) : add element x at the top of the queue
}
b) Queue ADT
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define max 100
template <class T>
class queue
{
T x;
int front,rear;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
7
public:
queue();
void insert(T);
T remove();
void display();
};
template <class T>
queue<T>::queue()
{
front=0;
rear=-1;
}
template <class T>
void queue<T>::insert(T n)
{
if(rear==max-1)
cout<<"queue is overflow"<<endl;
else
x[++rear]=n;
}
template <class T>
T queue<T>::remove()
{
if(rear<front)
{
cout<<"queue is empty"<<endl;
return 0;
}
else
return x[front++];
}
template <class T>
void queue<T>::display()
{
int i;
if(rear<front)
cout<<"queue is empty"<<endl;
else
{
cout<<"queue Elements are"<<endl;
for(i=front;i<=rear;i++)
cout<<x[i]<<"\t";
}
}
void main()
{
queue<int>obj;
int ch,n;
clrscr();
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
8
do
{
cout<<"\n1.insert \n 2.remove \n 3.Display \n 4.exit"<<endl;
cout<<"enter your choice"<<endl;
cin>>ch;
switch(ch)
{
case 1: cout<<"enter element to insert to the queue"<<endl;
cin>>n;
obj.insert(n);
break;
case 2:cout<<"removed element is"<<obj.remove()<<endl;
case 3:obj.display();
break;
case 4:exit(0);
default: cout<<"invalid choice";
}
}while(1);
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
9
2).Write C++ programs to implement the following using a singly linked list.
a) Stack ADT
#include<iostream.h>
#include<conio.h>
template <class T>
class stack
{
struct node
{
T data;
node *link;
}* top;
public:
stack();
void push(T);
T pop();
void display();
~stack();
};
template <class T>
stack<T>::stack()
{
top=0;
}
template <class T>
void stack<T>:: push(T x)
{
node *p=new node;
p->data=x;
p->link=top;
top=p;
}
template <class T>
T stack<T>::pop()
{
node *temp=top;
top=top->link;
T x=temp->data;
delete temp;
return x;
}
template <class T>
void stack<T>::display()
{
if(top==0)
cout<<"Empty stack"<<endl;
else
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
10
node* temp=top;
while(temp!=0)
{
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<endl;
}
}
template <class T>
stack<T>::~stack()
{
node *temp;
while(top!=0)
{
temp=top;
top=top->link;
delete temp;
}
}
void menu1()
{
cout<<"1.Interger stack"<<endl;
cout<<"2.Float stack"<<endl;
cout<<"3.Character stack"<<endl;
}
void menu2()
{
cout<<"1.Insert"<<endl;
cout<<"2.Delete"<<endl;
cout<<"3.Display"<<endl;
cout<<"4.Exit"<<endl;
}
template <class T>
void stackop(stack<T>st)
{
int ch;
T x,r;
menu2();
cin>>ch;
while(ch<4)
{
switch(ch)
{
case 1:
cout<<"Enter element"<<endl;
cin>>x;
st.push(x);
break;
case 2:
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
11
r=st.pop();
if(r==-1)
cout<<"Element cannot be deleted as stack
is empty"<<endl;
else
cout<<"Deleted element is "<<r<<endl;
break;
case 3:
st.display();
break;
}
menu2();
cin>>ch;
}
}
void main()
{
clrscr();
int ch;
menu1();
cin>>ch;
if(ch<4)
{
switch(ch)
{
case 1:
{
stack<int>s;
stackop(s);
break;
}
case 2:
{
stack<float>s;
stackop(s);
break;
}
case 3:
{
stack<char>s;
stackop(s);
break;
}
default :
break;
}
}
getch();
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
12
b) Queue ADT
#include <iostream.h>
#include <conio.h>
template <class T>
struct node
{
T data;
node *link;
};
template <class T>
class queue
{
node<T>*f,*r;
public:
queue();
void insert(T);
T del();
void display();
T first();
T last();
};
template <class T>
queue<T>::queue()
{
f=0;
r=0;
}
template <class T>
void queue<T>:: insert(T x)
{
node<T>*p=new node<T>;
p->data=x;
p->link=0;
if(f==0)
{
f=p;
r=p;
}
else
{
r->link=p;
r=p;
}
}
template <class T>
T queue<T>::del()
{
if(f==0)
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
13
return -1;
else
{
node<T>*temp=f;
T x=temp->data;
f=f->link;
return x;
}
}
template <class T>
void queue<T>::display()
{
if(f==0)
cout<<"Empty queue"<<endl;
else
{
node<T>*temp=f;
while(temp!=0)
{
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<endl;
}
}
template <class T>
T queue<T>::first()
{
if(f==0)
return -1;
else
return f->data;
}
template <class T>
T queue<T>::last()
{
if(f==0)
return -1;
else
return r->data;
}
void menu1()
{
cout<<"1.Interger queue"<<endl;
cout<<"2.Float queue"<<endl;
cout<<"3.Character queue"<<endl;
}
void menu2()
{
cout<<"1.Insert"<<endl;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
14
cout<<"2.Delete"<<endl;
cout<<"3.Display"<<endl;
cout<<"4.display first elemant"<<endl;
cout<<"5.display last element"<<endl;
cout<<"6.Exit"<<endl;
}
template <class T>
void queueop(queue<T>q)
{
int ch;
T x,r;
menu2();
cin>>ch;
while(ch<6)
{
switch(ch)
{
case 1:
cout<<"Enter element"<<endl;
cin>>x;
q.insert(x);
break;
case 2:
r=q.del();
if(r==-1)
cout<<"Element cannot be deleted as stack
is empty"<<endl;
else
cout<<"Deleted element is "<<r<<endl;
break;
case 3:
q.display();
break;
case 4:
r=q.first();
if(r==-1)
cout<<"Empty queue"<<endl;
else
cout<<"first element is"<<r<<endl;
break;
case 5:
r=q.last();
if(r==-1)
cout<<"Empty queue"<<endl;
else
cout<<"last element is"<<r<<endl;
break;
}
menu2();
cin>>ch;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
15
}
}
void main()
{
clrscr();
int ch;
menu1();
cin>>ch;
if(ch<4)
{
switch(ch)
{
case 1:
{
queue<int>q;
queueop(q);
break;
}
case 2:
{
queue<float>q;
queueop(q);
break;
}
case 3:
{
queue<char>q;
queueop(q);
break;
}
default :
break;
}
}
getch();
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
16
Doubly Linked Lists
One shortcoming of singly linked list is we can only move forwards through the list. A
doubly linked list is a linked list, which also has pointers from each element to the
preceding element. Doubly linked list make manipulation of lists easier.
DEQUE
A double-ended queue is a linear list for which insertions and deletions can occur at
either end i.e., deque supports insertion and deletion from the front and back.
The Deque Abstract Data Type
insertFirst(e): Insert e at the beginning of deque.
insertLast(e): Insert e at end of deque
removeFirst(): Removes and returns first element
removeLast(): Removes and returns last element
Additionally supported methods include:
To Implement Deque with Doubly Linked Lists we use a doubly linked list with special
header and trailer nodes
When implementing a doubly linked list, we add two special nodes to the ends of the
lists: the header and trailer nodes.
The header node goes before the first list element. It has a valid next link but a
null prev link.
The trailer node goes after the last element. It has a valid prev reference but a
null next reference.

NOTE: the header and trailer nodes are sentinel or dummy nodes because they do
not store elements. Heres a diagram of our doubly linked list:
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
17
03.Write C++ program to implement the deque (double ended queue) ADT
using
a doubly linked list.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
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
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
18
cout <<" Add element 1.FIRST 2.LAST\n enter ur choice:";
cin >>ch;
if(ch==1)
{
top1++;
temp=new node;
temp->data=x;
temp->next=head;
temp->prev=NULL;
head->prev=temp;
head=temp;
}
else
{
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
}
}
}
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;
}
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
19
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;
}
}
}
};
main()
{
dqueue d1;
int ch,x;
clrscr();
do
{
cout <<"\n1.INSERT 2.DELETE 3.DISPLAY 4.EXIT\n ";
cout<<"enter your choice"<<endl;
cin >>ch;
switch(ch)
{
case 1: cout <<"enter element";
cin >>x;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
20
d1.push(x); break;
case 2: d1.pop(); break;
case 3: d1.display(); break;
case 4: exit(1);
}
}while(1);
}
4. Write a C++ 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.
5.Write C++ programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.
TREES
A tree is a finite set of one or more nodes such that there is a specially designated node
called the root and the remaining nodes are partitioned into n0 disjoint sets T
1
, .,T
n
,
where each of these sets is a tree. The sets are called the subtrees of the root.
Binary Trees
Binary trees are characterized by the fact that any node can have at most two children;
i.e., there is no node with degree greater than two. A binary tree is a finite set of nodes
that is either empty or consists of a root and two disjoint binary trees called the left and
right subtrees.
ADT of binary tree
AbstractDataType binaryTree
{
instances
collection of elements; if not empty, the collection is partitioned into a root, left
subtree, and right subtree; each subtree is also a binary tree;
operations
empty( ) : return true if the stack is empty, return false otherwise;
size( ) : return the number of elements / nodes in the tree
preorder(visit) : preorder traversal of binary tree; visit is the visit function
to use;
inorder(visit) : inorder traversal of a binary tree
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
21
postorder(visit): postorder traversal of a binary tree.
}
Algorithms for non-recursive tree traversals.
Preorder traversal
1. define a stack
2. traverse the left sub-tree and output each visited node while pushing it in on the
stack until the leftmost node has been visited.
3. If the right subtree is not null, pop the stack, then visit that sub-tree. Output that
visited node while pushing it on the stack. If null, pop the stack.
4. Do 2and 3 until the stack is empty.
Inorder traversal
1. define a stack
2. traverse the left sub-tree and push each visited node on the stack until the
leftmost node has been visited.
3. If the right sub-tree in not null, pop the stack and output it, then visit the right
sub-tree and push it on the stack. If null, pop the stack and output it.
4. Do 2 and 3 until the stack is empty.
Postorder traversal
1. define a stack
2. traverse the left sub-tree and push each visited node on the stack until the
leftmost node has been visited.
3. If the right sub-tree in not null, visit the right sub-tree and push it on the stack. If
null, pop the stack and output it.
4. Do 2 and 3 until the stack is empty.
Binary Search Tree
A Binary search tree is a binary tree. It may be empty. If it not empty, then it satisfies
the following properties.
1. Every element has a key and no two elements have the same key.
2. The keys in the left subtree are smaller than the key in the root.
3. The keys in the right subtree are larger than the key in the root.
4. Theleft and right subtrees are also binary search trees.
ADT of Binary Search Tree
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
22
AbstractDataType bsTree
{
instances
binary trees, each node has a pair whose first component is a key and whose
second component is the value associated with the key; all keys are distinct;
keys in the left subtree of any node are smaller than the key in the node; those in
the right subtree are larger.
operations
find(k) : return the pair with the key k.
insert(p) : insert the pair p into the search tree
erase(k) : delete the pair with key k;
ascend( ): output all pairs in ascending order of key.
}
A binary search tree can support the operations search, insert and delete among others.
Searching a binary search tree : since the definition of a binary search tree is recursive,
it is easier to write a recursive search procedure.
Insertion into a binary search tree
If the root is 0, then the search tree contains no elements and the search is unsuccessful.
Otherwise, we compare x with the key in the root. If x equals thekey, then the search
terminates successfully. If x is less than the key in the root, then no element in the right
subtree can have key value x, and only the left subtree is to be searched. If x is larger
than the key in the root, only the right subtree needs to be searched.
#include <conio.h>
#include <process.h>
#include <iostream.h>
#include <alloc.h>
struct node
{
int ele;
node *left;
node *right;
};
typedef struct node *nodeptr;
class bstree
{
public:
void insert(int,nodeptr &);
void del(int,nodeptr &);
int deletemin(nodeptr &);
void find(int,nodeptr &);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
23
nodeptr findmin(nodeptr);
nodeptr findmax(nodeptr);
void copy(nodeptr &,nodeptr &);
void makeempty(nodeptr &);
nodeptr nodecopy(nodeptr &);
void preorder(nodeptr);
void inorder(nodeptr);
void postorder(nodeptr);
void preordernr(nodeptr);
void inordernr(nodeptr);
void postordernr(nodeptr);
void leftchild(int,nodeptr &);
void rightchild(int,nodeptr &);
};
void bstree::insert(int x,nodeptr &p)
{
if (p==NULL)
{
p =new node;
p->ele=x;
p->left=NULL;
p->right=NULL;
}
else
{
if (x <p->ele)
insert(x,p->left);
else if (x>p->ele)
insert(x,p->right);
else
cout<<"Element already Exits !";
}
}
void bstree:: del(int x,nodeptr &p)
{
nodeptr d;
if (p==NULL)
cout<<"Element not found ";
else if (x <p->ele)
del(x,p->left);
else if (x >p->ele)
del(x,p->right);
else if ((p->left ==NULL) && (p->right ==NULL))
{
d=p;
free(d);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
24
p=NULL;
}
else if (p->left ==NULL)
{
d=p;
free(d);
p=p->right;
}
else if (p->right ==NULL)
{
d=p;
p=p->left;
free(d);
}
else
p->ele=deletemin(p->right);
}
int bstree::deletemin(nodeptr &p)
{
int c;
if (p->left ==NULL)
{
c=p->ele;
p=p->right;
return c;
}
else
c=deletemin(p->left);
return c;
}
void bstree::copy(nodeptr &p,nodeptr &p1)
{
makeempty(p1);
p1=nodecopy(p);
}
void bstree::makeempty(nodeptr &p)
{
nodeptr d;
if (p!=NULL)
{
makeempty(p->left);
makeempty(p->right);
d=p;
free(d);
p=NULL;
}
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
25
nodeptr bstree::nodecopy(nodeptr &p)
{
nodeptr temp;
if (p ==NULL)
return p;
else
{
temp =new node;
temp->ele=p->ele;
temp->left =nodecopy(p->left);
temp->right =nodecopy(p->right);
return temp;
}
}
nodeptr bstree::findmin(nodeptr p)
{
if (p==NULL)
{
cout<<"Tree is empty !";
return p;
}
else
{
while (p->left !=NULL)
p=p->left;
return p;
}
}
nodeptr bstree::findmax(nodeptr p)
{
if (p==NULL)
{
cout<<"Tree is empty !";
return p;
}
else
{
while (p->right !=NULL)
p=p->right;
return p;
}
}
void bstree::find(int x,nodeptr &p)
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
26
{
if (p==NULL)
cout<<"Element not found !";
else
{
if (x <p->ele)
find(x,p->left);
else if ( x>p->ele)
find(x,p->right);
else
cout<<"Element Found !";
}
}
void bstree::preorder(nodeptr p)
{
if (p!=NULL)
{
cout<<p->ele<<"-->";
preorder(p->left);
preorder(p->right);
}
}
void bstree::inorder(nodeptr p)
{
if (p!=NULL)
{
inorder(p->left);
cout<<p->ele<<"-->";
inorder(p->right);
}
}
void bstree::postorder(nodeptr p)
{
if (p!=NULL)
{
postorder(p->left);
postorder(p->right);
cout<<p->ele<<"-->";
}
}
void bstree::leftchild(int q,nodeptr &p)
{
if (p==NULL)
cout<<"The node does not exists ";
else
if (q <p->ele )
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
27
leftchild(q,p->left);
else
if (q >p->ele)
leftchild(q,p->right);
else
if (q ==p->ele)
{
if (p->left !=NULL)
cout<<"Left child of "<<q<<"is "<<p->left->ele;
else
cout<<"No Left child !";
}
}
void bstree::rightchild(int q,nodeptr &p)
{
if (p==NULL)
cout<<"The nodedoes not exists ";
else
if (q <p->ele )
rightchild(q,p->left);
else
if (q >p->ele)
rightchild(q,p->right);
else
if (q ==p->ele)
{
if (p->right !=NULL)
cout<<"Right child of "<<q<<"is "<<p->right->ele;
else
cout<<"No Right Child !";
}
}
int main()
{
int ch,x,leftele,rightele;
bstree bst;
char c='y';
nodeptr root,root1,min,max;
root=NULL;
root1=NULL;
do
{
// system("clear");
clrscr();
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
28
cout<<"Binary Search Tree \n";
cout<<"------------------------- \n ";
cout<<" 1.Insertion \n 2.Deletion \n 3.NodeCopy \n ";
cout<<" 4.Find \n 5.Findmax \n 6.Findmin \n ";
cout<<" 7.Preorder \n 8.Inorder \n9.Postorder \n";
cout<<" 10.Leftchild \n 11.Rightchild \n 0.Exit \n ";
cout<<" \nEnter your choice :";
cin>>ch;
switch(ch)
{
case 1:
cout<<" 1.Insertion ";
cout<<"Enter the new element to get inserted : ";
cin>>x;
bst.insert(x,root);
cout<<"Inorder traversal is : ";
bst.inorder(root);
break;
case 2:
cout<<" 2.Deletion ";
cout<<"Enter the element to get deleted : ";
cin>>x;
bst.del(x,root);
bst.inorder(root);
break;
case 3:
cout<<" 3.Nodecopy ";
bst.copy(root,root1);
cout<<"The new tree is : ";
bst.inorder(root1);
break;
case 4:
cout<<" 4.Find ";
cout<<"Enter the element to be searched : ";
cin>>x;
bst.find(x,root);
break;
case 5:
cout<<" 5.Findmax ";
if (root ==NULL)
cout<<" Tree is empty";
else
{
max=bst.findmax(root);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
29
cout<<"Largest element is : "<<max->ele<<endl;
}
break;
case 6:
cout<<" 6.Findmin";
if (root ==NULL)
cout<<" Tree is empty";
else
{
min=bst.findmin(root);
cout<<"Smallest element is : "<<min->ele<<endl;
}
break;
case 7:
cout<<" 7.Preorder ";
if (root==NULL)
cout<<" Tree is empty";
else
{
cout<<"Preorder traversal (Recursive) is : ";
bst.preorder(root);
}
break;
case 8:
cout<<" 8.Inorder ";
if (root==NULL)
cout<<" Tree is empty";
else
{
cout<<" Inorder traversal (Recursive) is : ";
bst.inorder(root);
}
break;
case 9:
cout<<" 9.Postorder ";
if (root==NULL)
cout<<"Tree is empty";
else
{
cout<<"Postorder traversal (Recursive) is : ";
bst.postorder(root);
}
break;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
30
case 10:
cout<<" 10.Finding the left Child ";
if (root==NULL)
cout<<"Tree is empty";
else
{
cout<<"Enter the node for which the left child is to be
found : ";
cin>>leftele;
bst.leftchild(leftele,root);
}
break;
case 11:
cout<<" 11.Finding the Right Child";
if (root==NULL)
cout<<" Tree is empty";
else
{
cout<<"Enter the node for which the Right child is to be
found";
cin>>rightele;
bst.rightchild(rightele,root);
}
break;
case 0:
exit(0);
}
cout<<"\n Continue (y/n) ? ";
cin>>c;
}while (c=='y' || c =='Y');
return 0;
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
31
6.Write C++ programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.
#include <conio.h>
#include <process.h>
#include <iostream.h>
#include <alloc.h>
struct node
{
int ele;
node *left;
node *right;
};
typedef struct node *nodeptr;
class stack
{
private:
struct snode
{
nodeptr ele;
snode *next;
};
snode *top;
public:
stack()
{
top=NULL;
}
void push(nodeptr p)
{
snode *temp;
temp =new snode;
temp->ele =p;
temp->next =top;
top=temp;
}
void pop()
{
if (top !=NULL)
{
nodeptr t;
snode *temp;
temp =top;
top=temp->next;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
32
delete temp;
}
}
nodeptr topele()
{
if (top !=NULL)
return top->ele;
else
return NULL;
}
int isempty()
{
return ((top ==NULL) ? 1 : 0);
}
};
class bstree
{
public:
void insert(int,nodeptr &);
void del(int,nodeptr &);
int deletemin(nodeptr &p)
void preorder(nodeptr);
void inorder(nodeptr);
void postorder(nodeptr);
void preordernr(nodeptr);
void inordernr(nodeptr);
void postordernr(nodeptr);
};
void bstree::insert(int x,nodeptr &p)
{
if (p==NULL)
{
p =new node;
p->ele=x;
p->left=NULL;
p->right=NULL;
}
else
{
if (x <p->ele)
insert(x,p->left);
else if (x>p->ele)
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
33
insert(x,p->right);
else
cout<<"Element already Exits !";
}
}
void bstree:: del(int x,nodeptr &p)
{
nodeptr d;
if (p==NULL)
cout<<"Element not found ";
else if (x <p->ele)
del(x,p->left);
else if (x >p->ele)
del(x,p->right);
else if ((p->left ==NULL) && (p->right ==NULL))
{
d=p;
free(d);
p=NULL;
}
else if (p->left ==NULL)
{
d=p;
free(d);
p=p->right;
}
else if (p->right ==NULL)
{
d=p;
p=p->left;
free(d);
}
else
p->ele=deletemin(p->right);
}
int bstree::deletemin(nodeptr &p)
{
int c;
if (p->left ==NULL)
{
c=p->ele;
p=p->right;
return c;
}
else
c=deletemin(p->left);
return c;
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
34
void bstree::preorder(nodeptr p)
{
if (p!=NULL)
{
cout<<p->ele<<"-->";
preorder(p->left);
preorder(p->right);
}
}
void bstree::inorder(nodeptr p)
{
if (p!=NULL)
{
inorder(p->left);
cout<<p->ele<<"-->";
inorder(p->right);
}
}
void bstree::postorder(nodeptr p)
{
if (p!=NULL)
{
postorder(p->left);
postorder(p->right);
cout<<p->ele<<"-->";
}
}
void bstree::preordernr(nodeptr p)
{
stack s;
while (1)
{
if (p !=NULL)
{
cout<<p->ele<<"-->";
s.push(p);
p=p->left;
}
else
if (s.isempty())
{
cout<<"Stack is empty";
return;
}
else
{
nodeptr t;
t=s.topele();
p=t->right;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
35
s.pop();
}
}
}
void bstree::inordernr(nodeptr p)
{
stack s;
while (1)
{
if (p !=NULL)
{
s.push(p);
p=p->left;
}
else
{
if (s.isempty())
{
cout<<"Stack is empty";
return;
}
else
{
p=s.topele();
cout<<p->ele<<"-->";
}
s.pop();
p=p->right;
}
}
}
void bstree::postordernr(nodeptr p)
{
stack s;
while (1)
{
if (p !=NULL)
{
s.push(p);
p=p->left;
}
else
{
if (s.isempty())
{
cout<<"Stack is empty";
return;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
36
}
else
if (s.topele()->right ==NULL)
{
p=s.topele();
s.pop();
cout<<p->ele<<"-->";
if (p==s.topele()->right)
{
cout<<s.topele()->ele<<"-->";
s.pop();
}
}
if (!s.isempty())
p=s.topele()->right;
else
p=NULL;
}
}
}
int main()
{
int ch,x;
bstree bst;
char c='y';
nodeptr root;
root=NULL;
do
{
// system("clear");
clrscr();
cout<<"Binary Search Tree \n";
cout<<"------------------------- \n ";
cout<<" 1.Insertion \n 2.Deletion \n ";
cout<<" 3.Preorder \n 4.Inorder \n5.Postorder \n 6.Exit \n ";
cout<<" \nEnter your choice :";
cin>>ch;
switch(ch)
{
case 1:
cout<<" 1.Insertion ";
cout<<"Enter the new element to get inserted : ";
cin>>x;
bst.insert(x,root);
cout<<"Inorder traversal is : ";
bst.inorder(root);
break;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
37
case 2:
cout<<" 2.Deletion ";
cout<<"Enter the element to get deleted : ";
cin>>x;
bst.del(x,root);
bst.inorder(root);
break;
case 3:
cout<<" 3.Preorder ";
if (root==NULL)
cout<<" Tree is empty";
else
{
cout<<" Preorder traversal (Non-Recursive) is : ";
bst.preordernr(root);
cout<<"Preorder traversal (Recursive) is : ";
bst.preorder(root);
}
break;
case 4:
cout<<" 4.Inorder ";
if (root==NULL)
cout<<" Tree is empty";
else
{
cout<<" Inorder traversal (Non-Recursive) is :";
bst.inordernr(root);
cout<<" Inorder traversal (Recursive) is : ";
bst.inorder(root);
}
break;
case 5:
cout<<" 5.Postorder ";
if (root==NULL)
cout<<"Tree is empty";
else
{
cout<<"Postorder traversal (Non-Recursive) is : ";
bst.postordernr(root);
cout<<"Postorder traversal (Recursive) is : ";
bst.postorder(root);
}
break;
case 6:
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
38
exit(0);
}
cout<<" \n Continue (y/n) ? ";
cin>>c;
}while (c=='y' || c =='Y');
return 0;
}
GRAPHS
A graph can be thought of a collection of vertices (V) and edges (E), so we
write,
G =(V, E)
Graphs can be directed, or undirected, weighted or unweighted.
A directed graph, or digraph, is a graph where the edge set is an ordered pair.
That is, edge 1 being connected to edge 2 does not imply that edge 2 is
connected to edge 1. (i.e. it has direction trees are special kinds of directed
graphs)
An undirected graph is a graph where the edge set in an unordered pair.
That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to
edge 1.
A weighted graph is graph which has a value associated with each edge. This
can be a distance, or cost, or some other numeric value associated with the edge.
Breadth First Search and Traversal
In Breadth first search we start at vertex v and mark it as having been reached (visited)
the vertex v is at this time said to be unexplored. A vertex is said to have been explored
by an algorithm when the algorithm has visited all vertices adjacent from it. All
unvisited vertices adjacent from v are visited next. These are new unexplored vertices.
Vertex v has now been explored. The newly visited vertices have not been explored and
or put on to the end of a list of unexplored list of vertices. The first vertex on this list is
the next to be explored. Exploration continues until no unexplored vertex is left. The list
of unexplored vertices operates as a queue and can be represented using any of the
standard queue representations.
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
39
Algorithm BFS(v)
//A breadth first search of G is carried out beginning at vertex v. For
//any node I, visited[I=1 if I has already been visited. The graph G
//and array visited are global; visited[] is initialized to zero.
{
u:=v; //q is a queue of unexplored vertices
visited[v]:=1;
repeat
{
for all vertices w adjacent from u do
{
if (visited[w]=0) then
{
add w to q; //w is unexplored
visited[w]:=1;
}
}
if q is empty then return; //no unexplored vertex
delete u from q; //get first unexplored vertex
}until(false);
}
Algorithm BFT(G, n)
//Breadth first traversal of G
{
for I:=1 to n do //mark all vertices unvisited
visited[I]:=0;
for I:=1 to n do
if (visited[I]=0) then
BFS(i);
}
Depth First Search and Traversal
A depth first search of a graph differs from a breadth first search in that the exploration
of a vertex v is suspended as soon as a new vertex is reached. At this time of exploration
of the new vertex u begins. When this new vertex has been explored, the exploration of
v continues. The search terminates when all reached vertices have been fully explored.
The search process is best described recursively in the following algorithm.
Kruskals Algorithm
Here the edges of the graph considered in nondecreasing order of cost. This
interpretation is that the set t of edges so far selected for the spanning tree be such that it
is possible to complete t into a tree. Thus t may not be a tree at all stages of algorithm.
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
40
7.Write a C++ programs for the implementation of bfs and dfs for a given
graph.
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
void create(); // For creating a graph
void dfs(); // For Deapth First Search(DFS) Traversal.
void bfs(); // For Breadth First Search(BFS) Traversal.
struct node // Structurefor elements in the graph
{
int data,status;
struct node *next;
struct link *adj;
};
struct link // Structure for adjacency list
{
struct node *next;
struct link *adj;
};
struct node *start,*p,*q;
struct link *l,*k;
int main()
{
int choice;
clrscr();
create();
while(1)
{
cout<<"
-----------------------";
cout<<"
1: DFS
2: BSF
3: Exit
Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
dfs();
break;
case 2:
bfs();
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
41
break;
case 3:
exit(0);
break;
default:
cout<<"
Incorrect choice!
Re-enter your choice.";
getch();
}
}
return 0;
}
void create() // Creating a graph
{
int dat,flag=0;
start=NULL;
cout<<"
Enter the nodes in the graph(0 to end): ";
while(1)
{
cin>>dat;
if(dat==0)
break;
p=new node;
p->data=dat;
p->status=0;
p->next=NULL;
p->adj=NULL;
if(flag==0)
{
start=p;
q=p;
flag++;
}
else
{
q->next=p;
q=p;
}
}
p=start;
while(p!=NULL)
{
cout<<"Enter the links to "<<p->data<<" (0 to end) : ";
flag=0;
while(1)
{
cin>>dat;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
42
if(dat==0)
break;
k=new link;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==dat)
k->next=q;
q=q->next;
}
}
p=p->next;
}
cout<<"
-------------------------";
return;
}
// Deapth First Search(DFS) Traversal.
void bfs()
{
int qu,i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
qu=p->data;
p->status=1;
while(1)
{
if(qu[j]==0)
break;
p=start;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
43
while(p!=NULL)
{
if(p->data==qu[j])
break;
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
qu[i]=q->data;
q->status=1;
qu[i+1]=0;
i++;
}
k=k->adj;
}
j++;
}
j=0;
cout<<"
Breadth First Search Results
";
cout<<"
---------------------------
";
while(qu[j]!=0)
{
cout<<qu[j]<<" ";
j++;
}
getch();
return;
}
// Breadth First Search(BFS) Traversal.
void dfs()
{
int stack,top=1;
cout<<"
Deapth First Search Results
";
cout<<"
---------------------------
";
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
44
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
stack=0;
stack[top]=p->data;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==stack[top])
break;
p=p->next;
}
cout<<stack[top]<<" ";
top--;
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
top++;
stack[top]=q->data;
q->status=1;
}
k=k->adj;
}
}
getch();
return;
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
45
SORTING METHODS
HEAP SORT
The best-known example of the use of a heap arises in its application to sorting. A
conceptually simple sorting strategy has been given before, in which the maximum
value is continually removed from the remaining unsorted elements. A sorting
algorithm that incorporates the fact that n elements can be inserted I O(n) time is given
in the algorithm.
Algorithm HeapSort(a,n)
//a[1:n] contains n elements to be sorted. Heapsort
//rearranges them inplace into nondecreasing order.
{
heapify(a,n); //transform the array into a heap
//interchange the new maximum with the element
//at the end of the array.
for i:=n to 2 step 1 do
{
t:=a[i];
a[i]:=a;
a:=t;
adjust(a,1,i-1);
}
}
QUICK SORT
In quick sort, the division into two subarrays is made so that the sorted subarrays do no
need to be merged later. This is accomplished by rearranging the elements in a[1:n]
such that a[I] a[j] for all I between 1 and m and all j between m+1 and n for some m, 1
m n. Thus, the elements in a[1:m] and a[m+1:n] can be independently sorted. The
rearrangement of the elements is accomplished by picking some element of a[], say
t=a[s], and then reordering the other elements so that all elements appearing before t in
a[1:n] are less than or equal to t and all elements appearing after t are greater than or
equal to t. This rearranging is referred to as partitioning.
MERGE SORT
In merge sort, we assume throughout that the elements are to be sorted in nondecreasing
order. Given a sequence of n elements, the idea is to imagine them split into two sets
a to a[n/2] and a[n/2 +1] to a[n]. Each set is individually sorted, and the resulting
sorted sequences are merged to produce a single sorted sequence of n elements.
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
46
8.Write C++ programs for implementing the following sorting methods:
a) Merge Sort
#include<iostream>
#include<conio.h>
using namespace std;
void mergesort(int *,int,int);
void merge(int *,int,int,int);
int a,i,n,b;
main()
{
cout <<"\n enter no of elements";
cin >>n;
cout <<"enter the elements";
for(i=0;i<n;i++)
cin >>a[i];
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++];
i++;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
47
}
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];

}
b) Heap Sort
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define MAX 10
template<class T>
class heap
{
private:
T arr[MAX];
int n;
public:
heap();
void insert(T num);
void makeheap();
void heapsort();
void display();
};
template<class T>
heap<T>::heap()
{
n=0;
for(int i=0;i<MAX;i++)
arr[i]=0;
}
template<class T>
void heap<T>::insert(T num)
{
if(n<MAX)
{
arr[n]=num;
n++;
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
48
else
cout<<"array is full \n";
}
template<class T>
void heap<T>::makeheap()
{
for(int i=1;i<n;i++)
{
T val=arr[i];
int j=i;
int f=(j-1)/2;
while((j>0)&&(arr[f]<val))
{
arr[j]=arr[f];
j=f;
f=(j-1)/2;
}
arr[j]=val;
}
}
template<class T>
void heap<T>::heapsort()
{
for(int i=n-1;i>0;i--)
{
T temp=arr[i];
arr[i]=arr;
int k=0;
int j;
if(i==1)
j=-1;
else
j=1;
if(i>2&&arr>arr)
j=2;
while(j>=0&&temp<arr[j])
{
arr[k]=arr[j];
k=j;
j=2*k+1;
if(j+1<=j-1&&arr[j]<arr[j+1])
j++;
if(j>i-1)
j=-1;
}
arr[k]=temp;
}
}
template<class T>
void heap<T>::display()
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
49
{
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<"\n";
}
void main()
{
heap<int>obj;
int i,n,x;
clrscr();
cout<<"enter how many elements to want";
cin>>n;
cout<<"enter"<<n<<"elements";
for(i=0;i<n;i++)
{
cin>>x;
obj.insert(x);
}
cout<<"\n the elements are"<<endl;
obj.display();
obj.makeheap();
cout<<"\n heap elements"<<endl;
obj.display();
obj.heapsort();
cout<<"\n elements stored by heapsort"<<endl;
obj.display();
getch();
}
09.Write a C++program to perform the following operations
a) Insertion into a B-tree
b) Deletion from a B-tree
B-Trees
An m-way tree in which
The root has at least one key
Non-root nodes have at least m/2 subtrees (i.e., at least (m - 1)/2 keys)
All the empty subtrees (i.e., external nodes) are at the same level
B-tree of order 3 not a B-tree
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
50
B-trees are especially useful for trees stored on disks, since their height, and hence also
the number of disk accesses, can be kept small.
The growth and contraction of m-way search trees occur at the leaves. On the other
hand, B-trees grow and contract at the root.
Insertions
Insert the key to a leaf
Overfilled nodes should send the middle key to their parent, and split into two at
the location of the submitted key.
add 19
add 21
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
51
Deletions
Key that is to be removed from a node with non-empty subtrees is being
replaced with the largest key of the left subtree or the smallest key in the right
subtree. (The replacement is guaranteed to come from a leaf.)
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
52
remove 26
If a node becomes under staffed, it looks for a sibling with an extra key. If such
a sibling exist, the node takes a key from the parent, and the parent gets the extra
key from the sibling.
remove 22
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
53
If a node becomes under staffed, and it cant receive a key from a sibling, the
node is merged with a sibling and a key from the parent is moved down to the
node.
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
54
remove 18
10.Write a C++program to perform the following operations
a) Insertion into an AVL-tree
b) Deletion from an AVL-tree
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
55
AVL Trees
An AVL tree (also called an "admissible tree") is a tree in which the height of the left
and right subtrees of every node differ by at most one - referred to as "height-balanced".
Example AVL trees:
3 6 5
/ \ / \ / \
2 5 4 7 2 9
/ / \ / \
3 1 4 7 12
/ \ / \
3 8 11 14
/
10
Example non-AVL trees:
5 6 5
/ / \ / \
3 3 10 2 9
/ / \ / / \ / \
2 1 4 7 1 4 7 12
\ / / \
8 3 11 14
/
10
In order to indicate the differences between the heights of the right and left subtrees of a
given (root) node, a balance factor is defined for that node of the subtree.
We define the balance factor, BF:
BF =(height of right subtree - height of left subtree)
So, BF =-1, 0 or +1 for an AVL tree.
Balance factors for example AVL trees (node key values not shown):
0 -1 +1
/ \ / \ / \
0 0 -1 0 -1 -1
/ / / \
0 0 +1 0
\
0
When the AVL property is lost we can rebalance the tree via one of four rotations:
SingleRight Rotation (SRR):
A is the node that the rotation is performed on. This rotation is performed when A is
unbalanced to the left (the left subtree is 2 higher than the right subtree) and B is left-
heavy (the left subtree of B is 1 higher than the right subtree of B). T1, T2 and T3
represent subtrees (a node was added to T1 which made B leftheavy and unbalanced A).
A SRR at A B
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
56
/ \ ----------> / \
B T3 T1 A
/ \ / \
T1 T2 T2 T3
Single Left Rotation (SLR):
A is the node that the rotation is performed on. This rotation is performed when A is
unbalanced to the right (the right subtree is 2 higher than the left subtree) and B is right-
heavy (the right subtree of B is 1 higher than the left subtree of B). T1, T2 and T3
represent subtrees (a node was added to T3 which made B right-heavy and unbalanced
A).
A SLR at A B
/ \ ----------> / \
T1 B A T3
/ \ / \
T2 T3 T1 T2
Double Left Rotation (DLR):
C is the node that the rotation is performed on. This rotation is performed when C is
unbalanced to the left (the left subtree is 2 higher than the right subtree), A is right-
heavy (the right subtree of A is 1 higher than the left subtree of A) and B is left-heavy.
T1, T2, T3, and T4 represent subtrees (a node was added to T2 which made B left-
heavy, made A right-heavy and unbalanced C). This consists of a single left rotation at
node A, followed by a single right at node C.
C SLR at A C SRR at C B
/ \ ----------> / \ ---------> / \
A T4 B T4 A C
/ \ / \ / \ / \
T1 B A T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
That is, DLR equiv SLR +SRR
Double Right Rotation (DRR):
A is the node that the rotation is performed on. This rotation is performed when A is
unbalanced to the right (the right subtree is 2higher than the left subtree), C is leftheavy
(the left subtree of C is 1 higher than the right subtree of C) and B is right-heavy. T1,
T2, T3, and T4 represent subtrees (a node was added to T3 which made B right-heavy,
made C left-heavy and unbalanced A). This consists of a single right at node C,
followed by a single left at node A.
A SRR at C A SLR at A B
/ \ ----------> / \ ----------> / \
T1 C T1 B A C
/ \ / \ / \ / \
B T4 T2 C T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
57
That is, DRR equiv SRR +SLR
Insertion in a AVL-tree
An AVL tree may become out of balance in two basic situations:
1. After inserting a node in the right subtree of the right child.
2. After inserting a node in the left subtree of the right child.
Insertion of a node in the right subtree of the right child:
This involves a SLR about node P:
Insertion of a node in the left subtree of the right child:
This involves a DRR:
In each case the tree is rebalanced locally (since there is no need to modify the balance
factors higher in the tree).
Since rebalancing is local, insertion requires one single or one double rotation, ie
O(constant) for rebalancing.
Of course, there is still the cost of search for insertion (see below).
Experiments have shown that 53% of insertions do not bring the tree out of balance.
Example: Given the following AVL tree, insert the node with value 9:
6
/ \
3 12
\ / \
4 7 13
\
10
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
58
Insertion into an AVL tree may be carried out by inserting the given value into the tree
as if it were an unbalanced binary search tree, and then retracing one's steps toward the
root, rotating about any nodes which have become unbalanced during the insertion.
Deletion
Deletion from an AVL tree may be carried out by rotating the node to bedeleted down
into a leaf node, and then pruning off that leaf node directly. Since at most logn nodes
are rotated during the rotation into the leaf, and each AVL rotation takes constant time,
the deletion process in total takes O(logn) time.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <dos.h>
#include <string.h>
#include <graphics.h>
#include <conio.h>
struct node
{
int element;
node *left;
node *right;
int height;
};
typedef struct node *nodeptr;
void insert(int,nodeptr &);
void del(int, nodeptr &);
int deletemin(nodeptr &);
void find(int,nodeptr &);
nodeptr findmin(nodeptr);
nodeptr findmax(nodeptr);
void makeempty(nodeptr &);
nodeptr nodecopy(nodeptr &);
void preorder(nodeptr);
void inorder(nodeptr);
void postorder(nodeptr);
int bsheight(nodeptr);
nodeptr singlerotateleft(nodeptr &);
nodeptr doublerotateleft(nodeptr &);
nodeptr singlerotateright(nodeptr &);
nodeptr doublerotateright(nodeptr &);
int max(int,int);
int nonodes(nodeptr);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
59
int gdriver=DETECT,gmode=0,errorcode;
char element;
int x=1,maxx,midx,xcoord,ycoord,level=320,prevlevel;
void GDisplay(nodeptr p,int xcoord,int ycoord)
{
if (p!=NULL)
{
level=level/2;
setfillstyle(1,BROWN);
setcolor(LIGHTGREEN);
if(p->left->element!=NULL)
line(xcoord,ycoord,xcoord-level,ycoord+50);
if(p->right->element!=NULL)
line(xcoord,ycoord,xcoord+level,ycoord+50);
fillellipse(xcoord,ycoord,10,10);
sprintf(element,"%d",p->element,xcoord,ycoord);
settextstyle(2,0,4);
setcolor(YELLOW);
outtextxy(xcoord-7,ycoord-7,element);
GDisplay(p->left,xcoord-(level),ycoord+50);
GDisplay(p->right,xcoord+(level),ycoord+50);
level=level*2;
}
}//end of GDisplay
void insert(int x,nodeptr &p)
{
if (p ==NULL)
{
p =new node;
p->element =x;
p->left=NULL;
p->right =NULL;
p->height=0;
if (p==NULL)
{
gotoxy(4,21);
printf("Out of Space");
}
}
else
{
if (x<p->element)
{
insert(x,p->left);
//GDisplay(root,midx,50);
if ((bsheight(p->left) - bsheight(p->right))==2)
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
60
if (x <p->left->element)
p =singlerotateleft(p); //single rotation left
else
p =doublerotateleft(p); //double rotation left
}
}
else if (x>p->element)
{
insert(x,p->right);
//GDisplay(root,midx,50);
if ((bsheight(p->right) - bsheight(p->left))==2)
{
if (x >p->right->element)
p =singlerotateright(p); //single rotation right
else
p =doublerotateright(p); //double rotation right
}
}
else
{
gotoxy(4,21);
printf("Element Exists");
}
}
int m,n,d;
m=bsheight(p->left);
n=bsheight(p->right);
d=max(m,n);
p->height =d +1;
}
nodeptr findmin(nodeptr p)
{
if (p==NULL)
{
gotoxy(4,21); printf("Empty Tree");
return p;
}
else
{
while(p->left !=NULL)
p=p->left;
return p;
}
}
nodeptr findmax(nodeptr p)
{
if (p==NULL)
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
61
gotoxy(4,21); printf("Empty Tree");
return p;
}
else
{
while(p->right !=NULL)
p=p->right;
return p;
}
}
void find(int x,nodeptr &p)
{
if (p==NULL)
{
gotoxy(4,21);
printf("Element not found");
}
else if (x <p->element)
find(x,p->left);
else if (x>p->element)
find(x,p->right);
else
{
gotoxy(4,21);
printf("Element found !");
}
}
void del(int x,nodeptr &p)
{
nodeptr d;
if (p==NULL)
{
gotoxy(4,21);
printf("Element not found");
}
else if ( x <p->element)
{
del(x,p->left);
if ((bsheight(p->left) - bsheight(p->right))==2)
{
if (x <p->left->element)
p=singlerotateleft(p); //single rotation left
else
p =doublerotateleft(p); //double rotation left
}
}
else if (x >p->element)
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
62
del(x,p->right);
if ((bsheight(p->right) - bsheight(p->left))==2)
{
if (x >p->right->element)
p =singlerotateright(p); //single rotation right
else
p =doublerotateright(p); //double rotation right
}
}
else if ((p->left ==NULL) && (p->right ==NULL))
{
d=p;
free(d);
p=NULL;
gotoxy(4,21); printf("Element deleted !");
}
else if (p->left ==NULL)
{
d=p;
free(d);
p=p->right;
gotoxy(4,21); printf("Element deleted !");
}
else if (p->right ==NULL)
{
d=p;
p=p->left;
free(d);
gotoxy(4,21); printf("Element deleted !");
}
else
p->element =deletemin(p->right);
}
int deletemin(nodeptr &p)
{
int c;
gotoxy(4,21); printf("deltemin");
if (p->left ==NULL)
{
c=p->element;
p=p->right;
return c;
}
else
{
c=deletemin(p->left);
return c;
}
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
63
void preorder(nodeptr p)
{
if (p!=NULL)
{
printf("%d-->",p->element);
preorder(p->left);
preorder(p->right);
}
}
void inorder(nodeptr p)
{
if (p!=NULL)
{
inorder(p->left);
printf("%d-->",p->element);
inorder(p->right);
}
}
void postorder(nodeptr p)
{
if (p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("%d-->",p->element);
}
}
int max(int value1, int value2)
{
if(value1 >value2)
return value1;
else
return value2;
}
int bsheight(nodeptr p)
{
int t;
if (p ==NULL)
return -1;
else
{
t =p->height;
return t;
}
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
64
nodeptr singlerotateleft(nodeptr &p1)
{
nodeptr 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;
}
nodeptr singlerotateright(nodeptr &p1)
{
nodeptr 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;
}
nodeptr doublerotateleft(nodeptr &p1)
{
p1->left =singlerotateright(p1->left);
return singlerotateleft(p1);
}
nodeptr doublerotateright(nodeptr &p1)
{
p1->right =singlerotateleft(p1->right);
return singlerotateright(p1);
}
int count=0;
int nonodes(nodeptr p)
{
if (p!=NULL)
{
nonodes(p->left);
nonodes(p->right);
count++;
}
return count;
}
void twolinebox(int x1,int y1,int x2,int y2){
int x,y;
textcolor(WHITE);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
65
gotoxy(x1,y1); cprintf(""); //201
gotoxy(x2,y1); cprintf(""); //187
for(y=y1+1;y<y2;y++){
gotoxy(x1,y); cprintf(""); //186
gotoxy(x2,y); cprintf(""); //186
}
gotoxy(x1,y2); cprintf(""); //200
gotoxy(x2,y2); cprintf(""); //188
for(x=x1+1;x<x2;x++){
gotoxy(x,y1); cprintf(""); //205
gotoxy(x,y2); cprintf(""); //205
}
gotoxy(x1+1,y1+1);
}
void cprintxy(int x,int y,int color,char string[]){
textcolor(color);
gotoxy(x,y); cprintf("%s",string);
}
void center(int y,int color,char string[]){
int x=(80-strlen(string)+1)/2;
textcolor(color);
gotoxy(x,y);cprintf("%s",string);
}
void Temp(void){
int x,y;
clrscr();
twolinebox(1,1,80,24);
for(y=23;y>=1;y--){
sound(60*y);
center(y,YELLOW,"[Adelson-Velskii and Landis Tree]");
gotoxy(2,y+1); clreol();
twolinebox(1,1,80,24);
delay(40);
nosound();
}
center(1,YELLOW,"[Adelson-Velskii and Landis Tree]");
for(x=74;x>=3;x--){
sound(50*x);
cprintxy(x,5,RED,"Press:"); clreol();
twolinebox(1,1,80,24);
center(1,YELLOW,"[Adelson-Velskii and Landis Tree]");
delay(20);
nosound();
}
twolinebox(1,1,80,12);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
66
twolinebox(1,1,80,24);
center(1,YELLOW,"[Adelson-Velskii and Landis Tree]");
cprintxy(20,3,GREEN,"[A]- Insertion");
cprintxy(20,4,GREEN,"[B]- Find Minimum");
cprintxy(20,5,GREEN,"[C]- Find Maximum");
cprintxy(20,6,GREEN,"[D]- Search Node");
cprintxy(20,7,GREEN,"[E]- Display Tree");
cprintxy(43,3,GREEN,"[F]- Delete Node");
cprintxy(43,4,GREEN,"[G]- Preorder");
cprintxy(43,5,GREEN,"[H]- Inorder");
cprintxy(43,6,GREEN,"[I]- Postorder");
cprintxy(43,7,GREEN,"[J ]- Height");
cprintxy(20,9,GREEN,"[any key]- Quit...");
cprintxy(20,11,LIGHTRED,"Enter your choice: ");
}
void main()
{
nodeptr root,min,max;
int a,findele,delele,leftele,rightele,flag;
char choice,value;
char ch='Y';
root =NULL;
textmode(C80);
Temp();
do
{
clrscr();
twolinebox(1,1,80,12);
twolinebox(1,1,80,24);
center(1,YELLOW,"[Adelson-Velskii and Landis Tree]");
cprintxy(5,3,LIGHTRED,"Press: ");
cprintxy(20,3,GREEN,"[A]- Insertion");
cprintxy(20,4,GREEN,"[B]- Find Minimum");
cprintxy(20,5,GREEN,"[C]- Find Maximum");
cprintxy(20,6,GREEN,"[D]- Search Node");
cprintxy(20,7,GREEN,"[E]- Display Tree");
cprintxy(43,3,GREEN,"[F]- Delete Node");
cprintxy(43,4,GREEN,"[G]- Preorder");
cprintxy(43,5,GREEN,"[H]- Inorder");
cprintxy(43,6,GREEN,"[I]- Postorder");
cprintxy(43,7,GREEN,"[J ]- Height");
cprintxy(20,9,GREEN,"[any key]- Quit...");
cprintxy(20,11,LIGHTRED,"Enter your choice:\>");
choice=getch();
switch(toupper(choice))
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
67
case 'A':
do{
gotoxy(4,14); printf("Enter node value: ");
a=atoi(gets(value));
if(atoi(value)==0)
{
gotoxy(4,21); printf("Error!!! Enter a valid integer
value only.");
gotoxy(4,22); printf("Press any key to
continue...");
getch();
}
}while(atoi(value)==0);
insert(a,root);
gotoxy(4,15);
inorder(root);
/*
initgraph(&gdriver,&gmode,"c:\tc\bgi");
errorcode =graphresult();
maxx=getmaxx();
midx=maxx/2,xcoord=midx/2,ycoord=40;
if (errorcode !=grOk)
{
printf("Graphics error: %s
", grapherrormsg(errorcode));
printf("Press any key to stop");
getch();
exit(1);
}
cleardevice();
GDisplay(root,midx,50);
getch();
restorecrtmode();
*/
break;
case 'B':
if (root !=NULL)
{
min=findmin(root);
gotoxy(4,14); printf("Min element : %d",min->element);
}
break;
case 'C':
if (root !=NULL)
{
max=findmax(root);
gotoxy(4,14); printf("Max element : %d",max->element);
}
break;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
68
case 'D':
gotoxy(4,14); printf("Search node :");
scanf("%d",&findele);
if (root !=NULL)
find(findele,root);
break;
case 'E':
initgraph(&gdriver,&gmode,"c:\tc\bgi");
errorcode =graphresult();
maxx=getmaxx();
midx=maxx/2;
xcoord=midx/2;
ycoord=40;
if (errorcode !=grOk)
{
printf("Graphics error: %s
", grapherrormsg(errorcode));
printf("Press any key to stop");
getch();
exit(1);
}
cleardevice();
setbkcolor(LIGHTBLUE);
settextstyle(2,0,5);
outtextxy(20,10,"Adelson-Velskii and Landis Tree");
GDisplay(root,midx,50);
outtextxy(20,440,"Programmed by: Frederick Badion");
outtextxy(20,450,"Polytechnic University of the
Philippines");
outtextxy(20,460,"2nd year Bachelor of Science in
Computer
Science");
outtextxy(320,440,"A partial fulfilment for the subject:
");
outtextxy(320,450,"Design and Analysis of Algorithm");
outtextxy(320,460,"Prof. Ria Sagum -Chairperson BSCS-
CCMIT
PUP-Sta.Mesa");
getch();
restorecrtmode();
break;
case 'F':
gotoxy(4,14); printf("Delete Node: ");
scanf("%d",&delele);
del(delele,root);
getch();
initgraph(&gdriver,&gmode,"c:\tc\bgi");
errorcode =graphresult();
maxx=getmaxx();
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
69
midx=maxx/2,xcoord=midx/2,ycoord=40;
if (errorcode !=grOk)
{
printf("Graphics error: %s
", grapherrormsg(errorcode));
printf("Press any key to stop");
getch();
exit(1);
}
cleardevice();
setbkcolor(LIGHTBLUE);
settextstyle(2,0,5);
outtextxy(20,10,"Adelson-Velskii and Landis Tree");
GDisplay(root,midx,50);
getch();
restorecrtmode();
break;
case 'G':
gotoxy(4,14); printf(" Preorder Printing...");
gotoxy(4,15);
preorder(root);
break;
case 'H':
gotoxy(4,14); printf(" Inorder Printing...");
gotoxy(4,15);
inorder(root);
break;
case 'I':
gotoxy(4,14); printf(" Postorder Printing...");
gotoxy(4,15);
postorder(root);
break;
case 'J ':
gotoxy(4,14); printf(" Height and Depth:
%d",bsheight(root));
gotoxy(4,15); printf("No. of nodes: %d",nonodes(root));
break;
}
gotoxy(4,22); printf(" Do you want to continue (y/n)?");
ch=toupper(getch());
}while(ch!='N');
}
11.Write a C++program to implement Kruskals algorithm to generate a minimum
spanning tree.
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
70
#include <stdio.h>
struct EdgeStruct {
int v; // connects first node
int w; // connects second node
float length;
} Edge,Tree;
struct CityStruct {
char CityName;
int SetPointer;
int CountInSet;
} City ;
FILE * debug;
int EdgePos,EdgeCount;
int DebugFind (int CityNumber ) {
int v,Root;
v =CityNumber;
while (City[v].SetPointer !=v) {
v =City[v].SetPointer;
}
Root =v;
return Root;
}
int CityCount;
CleanString (char * s) {
int len;
len =strlen(s);
s[len-1] =0;
}
DumpCities () {
int i;
fprintf(debug, "Edge Pos %d\n",EdgePos);
for (i=0; i<CityCount;i++) {
fprintf(debug,"City Number #%d",i,City[i].CityName);fflush(debug);
fprintf(debug," SetPointer %d CountInSet %d Root Set %d\n",
City[i].SetPointer, City[i].CountInSet, DebugFind(i));fflush(debug);
}
fflush(debug);
}
int Union (int OneCityNumber, int TwoCityNumber ) {
if (City[OneCityNumber].CountInSet >City[TwoCityNumber].CountInSet) {
City[TwoCityNumber].SetPointer =Find(OneCityNumber);
}
else {
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
71
City[OneCityNumber].SetPointer =Find(TwoCityNumber);
}
City[OneCityNumber].CountInSet +=City[TwoCityNumber].CountInSet;
}
int Find (int CityNumber ) {
int i,List,ListCount,v,Root;
v =CityNumber;
ListCount =0;
while (City[v].SetPointer !=v) {
List[ListCount] =v;
v =City[v].SetPointer;
}
Root =v;
for (i=0;i<ListCount;i++) {
City[List[ListCount]].SetPointer =Root;
}
return Root;
}
int GetCityIndex(char * CityName,int * FoundFlag) {
int i =0;
int ReturnThis;
*FoundFlag =0;
while (i <CityCount) {
if (strcmp(City[i].CityName,CityName) ==0)
{
*FoundFlag =1;
ReturnThis =i;
}
i++;
}
return ReturnThis;
}
int TreeCount;
DumpTree() {
int i;
for (i=0;i<TreeCount;i++) {
fprintf(debug, "edge %d (%d,%d) Length %f\n",i,Tree[i].v,Tree[i].w,Tree[i].length);
}fflush(debug);
for (i=0;i<TreeCount;i++) {
fprintf(debug, "edge %d (%s,%s) Length %f\n",i,City[Tree[i].v].CityName,
City[Tree[i].w].CityName,Tree[i].length);
}fflush(debug);
}
main () {
FILE * edge,*CityFile;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
72
char NameVar ;
char FromCity;
char Dummy;
char ToCity;
struct EdgeStruct Temp;
int FoundFlag,i,j,k,FromCityIndex,ToCityIndex,SetOne,SetTwo;
float Mileage;
debug =fopen ("debug.out","w");
if (debug ==0 ) {
printf ("cannot open debugging file");
}
edge =fopen ("edge.in","r");
if (edge ==0 ) {
printf ("cannot open edge\n");
}
CityFile =fopen ("Kcity.in","r");
if (CityFile ==0 ) {
printf ("cannot open City File\n");
}
fgets(NameVar,sizeof(NameVar),CityFile);
CleanString(NameVar);
CityCount =0;
while(strcmp(NameVar,"stop")!=0) {
strcpy(City[CityCount].CityName,NameVar);
fgets(NameVar,sizeof(NameVar),CityFile);
City[CityCount].SetPointer =CityCount;
City[CityCount].CountInSet =1;
CleanString(NameVar);
CityCount++;
}
EdgeCount =0;
fgets(NameVar,sizeof(NameVar),edge);
CleanString(NameVar);
while (strcmp (NameVar,"stop")!=0 ) {
strcpy (FromCity,NameVar);
fgets(ToCity,sizeof(ToCity),edge);
CleanString(ToCity);
fscanf(edge,"%f",&Mileage);
fgets(Dummy,sizeof(Dummy),edge);

FromCityIndex =GetCityIndex(FromCity,&FoundFlag);
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
73
if (FoundFlag) {
ToCityIndex =GetCityIndex(ToCity ,&FoundFlag);
if (FoundFlag) {
Edge[EdgeCount].v =FromCityIndex;
Edge[EdgeCount].w =ToCityIndex;
Edge[EdgeCount].length =Mileage;
EdgeCount++;
}
}
if (!FoundFlag) {
printf( "City Not found in %s , %s \n",FromCity,ToCity);
}
fgets(NameVar,sizeof(NameVar),edge);
CleanString(NameVar);

}

// insertion sort the edges; of course, we would be better using an O(N Log N) sort
for (i=0;i<EdgeCount-1;i++) {
j=i+1;
while (j<EdgeCount) {
if (Edge[j].length<Edge[i].length) {
memcpy(&Temp,&(Edge[j]),sizeof(struct EdgeStruct));
memcpy(&(Edge[j]),&(Edge[i]),sizeof(struct EdgeStruct));
memcpy(&(Edge[i]),&Temp,sizeof(struct EdgeStruct));
}
j++;
}
}
TreeCount =0;
EdgePos =0;
while ( TreeCount <CityCount-1 && EdgePos <EdgeCount) {
DumpCities();
SetOne =Find(Edge[EdgePos].v);
SetTwo =Find (Edge[EdgePos].w);
if (SetOne !=SetTwo ) {
memcpy(&Tree[TreeCount],&Edge[EdgePos],sizeof(struct EdgeStruct));
Union(SetOne,SetTwo);
TreeCount++;
}
EdgePos++;
}
DumpCities();
DumpTree();
}
}
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
74
12.Write a C++program to implement Prims algorithm to generate a minimum
spanning tree.
#include<iostream.h>
class prims
{
private:
int n; //no of nodes
int graph_edge; //edges in the graph
int g; //no of edges in the graph
int tree_edge; //edges in the tree
int t; //no of edges in the tree
int s; //source node
//Partition the graph in to two sets
int T1,t1; // Set 1
int T2,t2; // Set 2
public:
void input();
int findset(int);
void algorithm();
void output();
};
void prims::input()
{
cout<<*************************************************\n
<<This program implements the prims algorithm\n
<<*************************************************\n;
cout<<Enter the no. of nodes in the undirected weighted graph ::;
cin>>n;
g=0;
cout<<Enter the weights for the following edges ::\n;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cout<< <<<i<< , <<j<< >::;
int w;
cin>>w;
if(w!=0)
{
g++;
graph_edge[g]=i;
graph_edge[g]=j;
graph_edge[g]=w;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
75
}
}
}
// print the graph edges
cout<<\n\nThe edges in the given graph are::\n;
for(i=1;i<=g;i++)
cout<< <<<graph_edge[i]
<< , <<graph_edge[i]
<< >::<<graph_edge[i]<<endl;
}
int prims::findset(int x)
{
for(int i=1;i<=t1;i++)
if(x==T1[i])
return 1;
for(i=1;i<=t2;i++)
if(x==T2[i])
return 2;
return -1;
}
void prims::algorithm()
{
t=0;
t1=1;
T1=1; //The source node
t2=n-1;
int i;
for(i=1;i<=n-1;i++)
T2[i]=i+1; //The reamining nodes
cout<<\n*****The algorithm starts*****\n\n;
while(g!=0 && t!=n-1)
{
// Find the least cost edge
int min=9999;
int p;
int u,v,w;
for(i=1;i<=g;i++)
{
bool flag1=false,flag2=false;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
76
//if u and v are in different sets
if(findset(graph_edge[i])!=findset(graph_edge[i]))
{
if(min>graph_edge[i])
{
min=graph_edge[i];
u=graph_edge[i];
v=graph_edge[i];
w=graph_edge[i];
p=i;
}
}
}
//break if there is no such edge
cout<<The edge included in the tree is ::;
cout<< <<<u<< , <<v<< ><<endl;
//delete the edge from graph edges
for(int l=p;l<g;l++)
{
graph_edge[l]=graph_edge[l+1];
graph_edge[l]=graph_edge[l+1];
graph_edge[l]=graph_edge[l+1];
}
g;
//add the edge to the tree
t++;
tree_edge[t]=u;
tree_edge[t]=v;
tree_edge[t]=w;
//Alter the set partitions
t1++;
int m;
if(findset(v)==2)
{
T1[t1]=v;
m=v;
}
else if(findset(u)==2)
{
T1[t1]=u;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
77
m=u;
}
int x;
for(x=1;T2[x]!=m;x++);
for(;x<t2;x++)
T2[x]=T2[x+1];
t2;
// Print the sets
int k;
cout<<NOW\nT1 :: ;
for(k=1;k<=t1;k++)
cout<<T1[k]<< ;
cout<<endl;
cout<<T2 :: ;
for(k=1;k<=t2;k++)
cout<<T2[k]<< ;
cout<<endl;
cout<<The graph edges are ::\n;
for(i=1;i<=g;i++)
cout<< <<<graph_edge[i]
<< , <<graph_edge[i]
<< >::<<graph_edge[i]<<endl;
cout<<endl<<endl;}}
void prims::output()
{
cout<<\nThe selected edgesare ::\n;
for(int i=1;i<=t;i++)
cout<< <<<tree_edge[i]
<< , <<tree_edge[i]
<< >::<<tree_edge[i]<<endl;
}
int main(){
prims obj;
obj.input();
obj.algorithm();obj.output();return 0;
}
DICTIONARIES
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
78
A dictionary is a collection of Pairs of the form (k,v) where k is a key and v is the value
associated with the key k . No two pairs in a dictionary have the same key.
The following operations are performed on a dictionary.
AbstractDataType Dictionary
{
instances
collection of pairs with distinct keys
operations
empty( ) : return true if the dictionary is empty;
size( ) : return the number of pairs in the dictionary
find(k) : return the pair with key k;
insert(p) : insert the pair p into the dictionary;
erase(k) : delete the pair with key k;
}
Eg: The class list for the data structures course is a dictionary with as many pairs as
students registered for the course. When a new student registers, a pair/record
corresponding to this student is inserted into the dictionary; when a student drops the
course, her record may be deleted. The student name may be used as the key; the
remaining information in a record is the value associated with the key.
A Dictionary may be maintained as an ordered linear list and can be represented
using skip lists. Another possibility for the representation of a dictionary is to use
hashing. This method uses a hash function to map dictionary pairs into positions in a
table called the hash table. In the ideal situation, if pair p has the key k and f is the hash
function, then p is stored in position f(k) of the table. Assume for now that each position
of the table can store at most one pair. To search for a pair with key k, we compute f(k)
and see whether a pair exists at position f(k) of the table. If so, we have found the
desired pair. If not, the dictionary contains no pair with the specified key k. in the
former case the pair may be deleted by making position f(k) of the table empty. In the
latter case the pair may be inserted by placing it in position f(k).
13.Write a C++program to implement all the functions of a dictionary (ADT) using
hashing.
Open hashing
#include<iostream.h>
#include<conio.h>
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
79
#include<process.h>
struct node
{
int data;
node *next;
//friend symbtable;
};
class symbtable
{
int buckets;
node **ht;
public:
symbtable(int s)
{
buckets=s;
ht=new node* [buckets];
for(int i=0;i<s;i++)
{
ht[i]=0;
}
}
int hashfun(int );
void init();
void insert(int);
void search(int);
void disp();
};
void symbtable::init()
{
for(int i=0;i<buckets;i++)
{
ht[i]->data=0;
ht[i]->next=0;
}
}
void symbtable::insert(int x)
{
int i=hashfun(x);
node *newnode,*last;
newnode=new node;
newnode->data=x;
newnode->next=0;
if(ht[i]->data==0)
{
ht[i]->data=0;
ht[i]->next=newnode;
}
else
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
80
last=ht[i]->next;
while(last->next!=0)
{
last=last->next;
}
last->next=newnode;
}
}
void symbtable::disp()
{
node *temp,*last;
for(int i=0;i<buckets;i++)
{
//cout<<ht[i]->data;
//if(ht[i].next!=0)
{
temp=ht[i]->next;
while(temp!=0)
{
cout<<"-->"<<temp->data;
temp=temp->next;
}
cout<<endl;
}
}}
int symbtable::hashfun(int x)
{
int i=x%5;
return i;
}
void symbtable::search(int x)
{
int i=hashfun(x);
node *temp;
int flag=0;
temp=ht[i]->next;
if(temp->data==x)
{
cout<<"ele found atloc"<<i;
flag=1;
}
else
{
temp=ht[i]->next;
while(temp!=0)
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
81
{
if(temp->data==x)
{
cout<<"ele found at location:"<<i;
flag=1;
}
temp=temp->next;
}
}
if(flag==0)
{
cout<<"ele not found...\n";
}}
main()
{
symbtable s(5);
int n,x;
while(x)
{
cout<<"enter choice :\n 1.insert..\n 2.serch..\n 3.display..\n 4.exit()..\n";
cin>>n;
switch(n)
{
case 1:cout<<"enter the ele to be inserted...\n";
cin>>x;
s.insert(x);
break;
case 2:
cout<<"enter the ele to be searched....";
cin>>x;
s.search(x);
break;
case 3:
s.disp();
break;
case 4:
exit(1);
}
}
}
Closed hashing
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class symboltable
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
82
int buckets;
int *ht;
public
:
symboltable(int s)
{buckets =s;
ht=new int[buckets];
}
void init();
void dis();
int hashfun(int);
void search(int );
void insert(int);
};
void symboltable::init()
{
for(int i=0;i<buckets;i++)
{
ht[i]=0;
}
}
int symboltable::hashfun(int x)
{
int i=x%10;
return(i);
}
void symboltable::insert(int x)
{
int i=hashfun(x);
int j;
if(ht[i]==0)
{
ht[i]=x;
}
else
{
j=i;
do
{
j=(j+1) % buckets;
if(ht[j]==0)
{
ht[j]=x;
break;
} }
while (j!=i);
}
}
void symboltable::search(int x)
{
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
83
int i=hashfun(x);
int flag=0;
int j;
if(ht[i]==x)
{
cout<<"element found at location: "<<i;
flag=1;
}
else
{
j=i;
do
{
j=(j+1) %buckets;
if(ht[j]==x)
{
cout<<"element found at location :"<<j;
flag=1;
break;
}
}
while(j!=i);
if(flag==0)
{
cout<<"element not found... \n";
}
}
}
void symboltable::dis()
{
cout<<"values :"<<endl;
for(int i=0;i<buckets;i++)
cout<<ht[i]<<endl;
}
void main()
{
symboltable s(10);
clrscr();
s.init();
int n,x;
while(1)
{
cout<<"enter the choice in \n 1.insert \n 2. serch \n 3. disp.. \n 4.exit ..\n";
cin>>n;
switch(n)
{
case 1:
cout<<"enter ele to insert :..";
cin>>x;
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology
84
s.insert(x);
break;
case 2:
cout<<"enter ele to be search....";
cin>>x;
s.search(x);
break;
case 3:
s.dis();
break;
case 4:
exit(1);
}}}