You are on page 1of 81

Data Structures Through C++ Lab LAB MANUAL

R.V Ramana Chary Department Of IT BVRIT


1

ADVANCED DATA STRUCTURES AND ALGORITHMS (C++) LAB


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.
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
2


Templates

Template Functions
Suppose we want to write a function that finds the maximum of two objects. To find the
maximum of two integers we would write:
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 Item is a data type that
will be filled in later. The "unspecified type" Item is 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

www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
3
The maximal function is said to be instantiated with the data type Item set to int.
Similarly, we could do:
cout << maximal('a', 'z') << endl; // will print 'z'

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 Item type. 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 Item data 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
Item Bag<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





www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
4


STACKS AND QUEUES

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 same order.

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[0], the second at stack[1], 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>
class stack
{
int m;
int top;
int *s;
rear front
top
E
D
C
B
A
A B C D E
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
5
public :
stack(int);
void push(int);
int pop();
int isempty();
int isfull();
void display();
~stack();
};
stack::stack(int maxsize)
{
m=maxsize;
top=-1;
s=new int(m);
}
void stack::push(int x)
{
if(isfull())
cout<<"Stack is full"<<endl;
else
{
top++;
s[top]=x;
}
}
int stack ::pop()
{
if(isempty())
return -1;
else
{
int x=s[top];
top--;
return x;
}
}
int stack::isempty()
{
if(top==-1)
return 1;
else
return 0;
}
int stack :: isfull()
{
if(top==m-1)
return 1;
else
return 0;
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
6
void stack::display()
{
if(isempty())
cout<<"Empty list"<<endl;
else
{
for(int i=top;i>=0;i--)
cout<<s[i]<<" ";
cout<<endl;
}
}
stack::~stack()
{
delete [] s;
}
void menu()
{
cout<<"1.Insert"<<endl;
cout<<"2.Delete"<<endl;
cout<<"3.Display"<<endl;
cout<<"4.Exit"<<endl;
}
void main()
{
clrscr();
int ch;
int x,r;
stack st(10);
menu();
cin>>ch;
while(ch<4)
{
switch(ch)
{
case 1:
cout<<"Enter element"<<endl;
cin>>x;
st.push(x);
break;
case 2:
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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
7
}
menu();
cin>>ch;
}
getch();
}


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>
template <class T>
class queue
{
int m;
int f,r;
T *q;
public:
queue();
void insert(T);
T del();
int isfull();
int isempty();
void display();
T first();
T last();
};
template <class T>
queue<T>::queue()
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
8
{
f=0;
r=-1;
q=new T(10);
m=10;
}
template <class T>
int queue<T>::isempty()
{
if(r==-1)
return 1;
else
return 0;
}
template <class T>
int queue<T>::isfull()
{
if(r==m-1)
return 1;
else
return 0;
}
template <class T>
void queue<T>::insert(T x)
{
if(isfull())
cout<<"queue full"<<endl;
else
{
r++;
q[r]=x;
}
}
template <class T>
T queue<T>::del()
{
T x;
if(isempty())
return -1;
else
if(r==f)
{
x=q[f];
r=-1;
f=0;
return x;
}
else
{
x=q[f];
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
9
f++;
return x;
}
}
template <class T>
T queue<T>::first()
{
if(isempty())
return -1;
else
return q[f];
}
template <class T>
T queue<T>::last()
{
if(isempty())
return -1;
else
return q[r];
}
template <class T>
void queue<T>::display()
{
if(r==-1)
cout<<"Empty queue"<<endl;
else
{
for(int i=f;i<=r;i++)
cout<<q[i]<<" ";
cout<<endl;
}
}
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.display first elemant"<<endl;
cout<<"5.display last element"<<endl;
cout<<"6.Exit"<<endl;
}
template <class T>
void queueop(queue<T> q)
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
10
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;
}
}

void main()
{
clrscr();
int ch;
menu1();
cin>>ch;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
11
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();
}






















www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
12

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
{
node* temp=top;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
13
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:
r=st.pop();
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
14
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();
}

www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
15
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)
return -1;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
16
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;
cout<<"2.Delete"<<endl;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
17
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;
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
18
}

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














www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
19
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:











www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
20


03.Write C++ program to implement the deque (double ended queue) ADT using
a doubly linked list.

#include<iostream.h>
#include<conio.h>
struct node
{
node *llink;
int data;
node *rlink;
};
class dlink
{
node *l;
node *r;
public:
dlink();
void append(int);
void display();
int isempty();
int length();
int insert(int,int);
int del(int i,int& x);
int find(int i,int& x);
int search(int& i,int x);
};
dlink::dlink()
{
l=0;
r=0;
}
void dlink::append(int x)
{
node *temp,*p;
p=new node;
p->data=x;
if(l==0)
{
p->llink=0;
p->rlink=0;
l=p;
r=p;
}
else
{
r->rlink=p;
p->llink=r;
p->rlink=0;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
21
r=p;
}
}
void dlink::display()
{
node *temp;
if(l==0)
cout<<"emptylist"<<endl;
else
{
temp=l;
while(temp!=0)
{
cout<< temp->data<<" ";
temp=temp->rlink;
}
}
}
int dlink::isempty()
{
if((l==0)&&(r==0))
return 1;
else
return 0;
}
int dlink::length()
{
if(isempty())
return 0;
else
{
int len=1;
node *temp=l;
while(temp->rlink!=0)
{
len++;
temp=temp->rlink;
}
return len;
}
}
int dlink::insert(int i,int x)
{
if(i<0||i>length())
return 0;
else
{
node *p;
p=new node;
p->data=x;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
22
if(l==0)
{
p->llink=0 ;
p->rlink=0;
l=p;
r=p;
}
else
if(i==0)
{
p->rlink=l;
p->llink=0;
l->llink=p;
l=p;
}
else
if(i==length())
{
p->llink=r;
p->rlink=0;
r->rlink=p;
r=p;
}
else
{
node *temp=l;
for(int j=1;j<i;j++)
temp=temp->rlink;
p->llink=temp;
p->rlink=temp->rlink;
temp->rlink=p;
(temp->rlink)->llink=p;
}
return 1;
}
}


int dlink::del(int i,int& x)
{
if(i<1||i>length())
return 0;
else
{
node *temp;
if(length()==1)
{
temp=l;
l=0;
r=0;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
23
x=temp->data;
delete temp;
}
else
if(i==1)
{
temp=l;
l=l->rlink;
x=temp->data;
delete temp;
}
else
if(i==length())
{
temp=r;
r=r->llink;
r->rlink=0;
x=temp->data;
delete temp;
}
else
{
node *prev,*next;
temp=l;
for(int j=1;j<i;j++)
temp=temp->rlink;
prev=temp->llink;
next=temp->rlink;
prev->rlink=next;
next->llink=prev;
x=temp->data;
delete temp;
}
return 1;
}
}
int dlink::find(int i,int& x)
{
if(i<1||i>length())
return 0;
else
{
node *temp;
temp=l;
for(int j=1;j<i;j++)
temp=temp->rlink;
x=temp->data;
return 1;
}
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
24

int dlink::search(int& i,int x)
{
if(isempty())
return 0;
else
{
node *temp=l;
int len=1;
while(temp!=0)
{
if(temp->data==x)
{
i=len;
return 1;
}
else
{
len++;
temp=temp->rlink;
}
}
return 0;
}
}

void menu()
{
cout<<"Enter 1 to append"<<endl;
cout<<"Enter 2 to display"<<endl;
cout<<"Enter 3 to insert"<<endl;
cout<<"Enter 4 to delete"<<endl;
cout<<"Enter 5 to find the ith element"<<endl;
cout<<"Enter 6 to search for an element"<<endl;
cout<<"Enter 7 to exit"<<endl;
}
void main()
{
clrscr();
dlink dl;
int choice,i,x,r;
menu();
cin>>choice;
while(choice<7)
{
switch(choice)
{
case 1:
{
cout<<"Enter the element to be appended"<<endl;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
25
cin>>x;
dl.append(x);
break;
}
case 2:
{
dl.display();
break;
}
case 3:
{
cout<<"Enter the position and element"<<endl;
cin>>i>>x;
r=dl.insert(i,x);
if(r==0)
cout<<"Invalid position"<<endl;
else
cout<<"Element inserted"<<endl;
break;
}

case 4:
{
cout<<"Enter the position"<<endl;
cin>>i;
r=dl.del(i,x);
if(r==0)
cout<<"Invalid position"<<endl;
else
cout<<"deleted element is "<<x<<endl;
break;
}
case 5:
{
cout<<"Enter the position"<<endl;
cin>>i;
r=dl.find(i,x);
if(r==0)
cout<<"Invalid position"<<endl;
else
cout<<i<<"th element is "<<x<<endl;
break;
}
case 6:
{
cout<<"Enter the element to search"<<endl;
cin>>x;
r=dl.search(i,x);
if(r==0)
cout<<"Element not found"<<endl;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
26
else
cout<<"Element found in "<<i<<" position"<<endl;
break;
}
}
menu();
cin>>choice;
}
getch();
}

5).Write a C++ program to implement circular queue ADT using an array
CIRCULAR QUEUES

Removing an element from the queue is an expensive operation because all remaining elements
have to be moved by one position. A more efficient implementation is obtained if we consider
the array as being circular:


Implementation of circular queues using arrays

Algorithm Add!(item)
// insert item in the circular queue stored in q[0 : n-1].
//rear points to the last item, and front is one position
// counter clock wise from the first item in q.
{
rear := (rear + 1) mod n; // advance rear clock wise
if (front = rear) then
{
write (queue is full);
if (front=0) then rear:=n-1;
else rear:=rear-1;
//move rear one position counter clockwise.
return false.
}
else
{
q[rear]:=item;
return true
}
}

Algorithm DeleteQ()
// Removes and returns the front element of the queue q[0 : n-1].
{
if (front=rear) then
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
27
{
write (queue is empty);
return false;
}
else
{
front := (front +1) mod n // advance front clockwise
item := q[front];
return true;
}
}


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.
6.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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
28
inorder(visit) : inorder traversal of a binary tree
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 2 and 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. The left and right subtrees are also binary search trees.

ADT of Binary Search Tree
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
29

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 the key, 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.


6.Write C++ programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.


#include<iostream.h>
#include<conio.h>
struct node
{
node *lchild;
int data;
node *rchild;
// friend class bintree;
};
class stack
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
30
int m;
int top;
node **s;
public :
stack(int);
void push(node *);
node * pop();
int isempty();
int isfull();
// void display();
// ~stack();
};
stack::stack(int maxsize)
{
m=maxsize;
top=-1;
s=new node*[m];
}
void stack::push(node *x)
{
if(isfull())
cout<<"Stack is full"<<endl;
else
{
top++;
s[top]=x;
}
}
node* stack ::pop()
{
/* if(isempty())
return -1;
else*/
{
node *x=s[top];
top--;
return x;
}
}
int stack::isempty()
{
if(top==-1)
return 1;
else
return 0;
}
int stack :: isfull()
{
if(top==m-1)
return 1;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
31
else
return 0;
}
/*void stack::display()
{
if(isempty())
cout<<"Empty list"<<endl;
else
{
for(int i=top;i>=0;i--)
cout<<s[i]<<" ";
cout<<endl;
}
}
stack::~stack()
{
delete [] s;
}*/
class bintree
{
node *root;
public:
bintree();
void create(int);
void del(int x);
void preorder();
void preorder(node*);
void inorder(node*);
void postorder(node*);
void traversal();
int nodect();
int leafct();
int nle(node *);
int depth(node *);
};
bintree::bintree()
{
root=0;
}
void bintree::del(int x)
{
node *head;
node *pre,*p,*q;
head= new node;
head->lchild=root;
head->rchild=0;
pre=head;
p=pre->lchild;
while((p!=0)&&(p->data!=x))
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
32
pre=p;
if(x<p->data)
p=p->lchild;
else
p=p->rchild;

}
if((pre->rchild==p)&&(p->rchild==p->lchild))
pre->rchild=0;
else if((pre->lchild==p)&&(p->rchild==p->lchild))
pre->lchild=0;
else if(p->rchild==0)
pre->lchild=p->lchild;
else if(p->lchild==0)
pre->rchild=p->rchild;
else if((p->lchild!=0)&&(p->rchild!=0))
{
if(pre->lchild==p)
{
pre->lchild=p->rchild;
//node *q;
q=p->rchild;
while(q->lchild!=0)
q=q->lchild;
q->lchild=p->lchild;
}
else if(pre->rchild==p)
{
pre->rchild=p->rchild;
q=p->rchild;
while(q->lchild!=0)
q=q->lchild;
q->lchild=p->lchild;
}
}
cout<<"\n"<<p->data<<endl;
delete p;
root=head->lchild;
delete head;
}

void bintree::create(int x)
{
node *p,*temp,*parent;
p=new node;
p->data=x;
p->lchild=0;
p->rchild=0;
if(root==0)
root=p;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
33
else
{
temp=root;
while(temp!=0)
{
parent=temp;
if(p->data<temp->data)
temp=temp->lchild;
else
temp=temp->rchild;
}
if(p->data<parent->data)
parent->lchild=p;
else
parent->rchild=p;
}
}
void bintree:: traversal()
{
int ch,x;
cout<<"Enter your choice"<<endl;
cout<<"1,4.preorder"<<endl;
cout<<"2. inorder"<<endl;
cout<<"3. postorder"<<endl;
cout<<"5. number of lev.."<<endl;
cout<<"6. depth of tree is "<<endl;
cout<<"7. delete the element...."<<endl;
cin>>ch;
while(ch<8)
{
switch(ch)
{
case 1:
preorder();
break;
case 2:
inorder(root);
break;
case 3:
postorder(root);
break;
case 4:
preorder(root);
break;
case 5:int r=nle(root);
cout<<"rec leaves are " <<r<<endl;
break;
case 6:r=depth(root);
cout<<"rec depth of tree... " <<r<<endl;
break;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
34
case 7:cout<<"in order "<<endl;
inorder(root);
cout<<"\n enter the ele...."<<endl;
cin>>x;
del(x);
cout<<"\n after del..\n";
inorder(root);
break;
}
cout<<"enter your choice"<<endl;
cin>>ch;
}
}
void bintree:: preorder()
{
stack st(10);
node *p=root;
st.push(0);
while(p!=0)
{
cout<<p->data<<" ";
if(p->rchild!=0)
st.push(p->rchild);
if(p->lchild!=0)
p=p->lchild;
else
p=st.pop();
}
cout<<endl;
}
int bintree:: nodect()
{
stack st(10);
node *p=root;
st.push(0);
int count=0;
while(p!=0)
{
count++;
if(p->rchild!=0)
st.push(p->rchild);
if(p->lchild!=0)
p=p->lchild;
else
p=st.pop();
}
cout<<endl;
return count;
}
int bintree:: leafct()
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
35
{
stack st(10);
node *p=root;
st.push(0);
int count=0;
while(p!=0)
{
if((p->lchild==0)&&(p->rchild==0))
count++;
if(p->rchild!=0)
st.push(p->rchild);
if(p->lchild!=0)
p=p->lchild;
else
p=st.pop();
}
cout<<endl;
return count;
}
int bintree::nle(node *root)
{
node *p;
p=root;
if(p==0)
return(0);
else
if(p->lchild==p->rchild)
return(1);
else
return((nle(p->lchild))+(nle(p->rchild)));
}
int max(int x,int y)
{ if(x>y)
return(x);
else
return(y);
}

int bintree::depth(node *root)
{
node *p;
p=root;
if(p==0)
return(0);
else
if(p->lchild==p->rchild)
return(0);
else
return(1+max(depth(p->lchild),depth(p->rchild)));
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
36
void bintree:: inorder(node *temp)
{
if(temp!=0)
{
inorder(temp->lchild);
cout<<temp->data<<" ";
inorder(temp->rchild);
}
}
void bintree:: preorder(node *temp)
{
if(temp!=0)
{ cout<<temp->data<<" ";
preorder(temp->lchild);

preorder(temp->rchild);
} }
void bintree:: postorder(node *temp)
{
if(temp!=0)
{
postorder(temp->lchild);
postorder(temp->rchild);
cout<<temp->data<<" ";
}
}
void main()
{
clrscr();
int x,r;
char ch='y';
bintree bt;
while(ch=='y')
{
cout<<"Enter the element";endl;
cin>>x;
bt.create(x);

cout<<"Do u want to continue"<<endl;
cin>>ch;
}
r=bt.nodect();
cout<<"No of nodes are "<<r<<endl;
r=bt.leafct();
cout<<"No of leaves are "<<r<<endl;

bt.traversal();

getch();
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
37





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.

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.
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
38
{
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.


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.
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
39
void bfs(); // For Breadth First Search(BFS) Traversal.

struct node // Structure for 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();
break;
case 3:
exit(0);
break;
default:
cout<<"
Incorrect choice!
Re-enter your choice.";
getch();
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
40
}
}
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;
if(dat==0)
break;
k=new link;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
41
}
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[20],i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
qu[0]=p->data;
p->status=1;
while(1)
{
if(qu[j]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==qu[j])
break;
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
42
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[25],top=1;
cout<<"

Deapth First Search Results
";
cout<<"
---------------------------
";
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
stack[0]=0;
stack[top]=p->data;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
43
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;
}
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
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
44
{
t:=a[i];
a[i]:=a[1];
a[1]:=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[1] 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.




8.Write C++ programs for implementing the following sorting methods:
a) Quick sort
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
void quick(int a[],int l,int r)
{
if(l>=r)
return;
int i=l;
int j=r+1;
int v=a[l];
while(1)
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
45
{
do
{
i++;
}while(a[i]<v);
do
{
j--;
}while(a[j]>v);
if(i<j)
swap(a[i],a[j]);
else
break;
}
a[l]=a[j];
a[j]=v;
quick(a,l,j-1);
quick(a,j+1,r);
}
void main()
{
clrscr();
int n,*a,i;
cout<<"Enter the size of array"<<endl;
cin>>n;
a=new int[n];
cout<<"Enter the elements of array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
quick(a,0,n-1);

for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
}

b) Merge sort


c) Heap sort
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int t=x;
x=y;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
46
y=t;
}
void adjust(int a[],int i,int n)
{
int j=2*i+1;
while(j<=n)
{
if(j<n)
if(a[j]<a[j+1])
j++;
if(a[i]<a[j])
swap(a[i],a[j]);
else
break;
i=j;
j=2*i+1;
}
}
void hsort(int a[],int n)
{
int i;
for(i=n/2-1;i>=0;i--)
adjust(a,i,n);
for(i=n;i>=0;i--)
{
swap(a[0],a[i]);
adjust(a,0,i-1);
}
}
void main()
{
clrscr();
int n,*a,i;
cout<<"Enter the size of array"<<endl;
cin>>n;
a=new int[n];
cout<<"Enter the elements of array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
hsort(a,n-1);

for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
}

www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
47
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

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.


www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
48
add 19

add 21







www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
49


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


remove 26





www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
50
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







www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
51


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.


remove 18







www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
52






10.Write a C++ program to perform the following operations
a) Insertion into an AVL-tree
b) Deletion from an AVL-tree



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.
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
53

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:

Single Right 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
/ \ ----------> / \
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):
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
54
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), 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
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).
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
55
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

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 be deleted down into a leaf node,
and then pruning off that leaf node directly. Since at most log n nodes are rotated during the rotation into
the leaf, and each AVL rotation takes constant time, the deletion process in total takes O(log n) 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 &);
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
56
nodeptr doublerotateleft(nodeptr &);
nodeptr singlerotateright(nodeptr &);
nodeptr doublerotateright(nodeptr &);
int max(int,int);
int nonodes(nodeptr);


int gdriver=DETECT,gmode=0,errorcode;
char element[3];
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
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
57
{
if (x<p->element)
{
insert(x,p->left);
//GDisplay(root,midx,50);
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)
{
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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
58
}
}

nodeptr findmax(nodeptr p)
{
if (p==NULL)
{
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)
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
59
p = singlerotateleft(p); //single rotation left
else
p = doublerotateleft(p); //double rotation left
}
}
else if (x > p->element)
{
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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
60
}
else
{
c=deletemin(p->left);
return c;
}
}

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)
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
61
return -1;
else
{
t = p->height;
return t;
}
}

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++;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
62
}
return count;
}

void twolinebox(int x1,int y1,int x2,int y2){
int x,y;
textcolor(WHITE);
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);
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
63
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);
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[2];
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");
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
64
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))
{
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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
65
case 'C':
if (root !=NULL)
{
max=findmax(root);
gotoxy(4,14); printf("Max element : %d",max->element);
}
break;
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':
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
66
gotoxy(4,14); printf("Delete Node: ");
scanf("%d",&delele);
del(delele,root);
getch();
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);
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());
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
67
}while(ch!='N');
}


11.Write a C++ program to implement Kruskals algorithm to generate a minimum
spanning tree.

#include <stdio.h>
struct EdgeStruct {
int v; // connects first node
int w; // connects second node
float length;
} Edge[100],Tree[100];


struct CityStruct {
char CityName[80];
int SetPointer;
int CountInSet;
} City [100];

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);
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
68
}

int Union (int OneCityNumber, int TwoCityNumber ) {
if (City[OneCityNumber].CountInSet > City[TwoCityNumber].CountInSet) {
City[TwoCityNumber].SetPointer = Find(OneCityNumber);
}
else {
City[OneCityNumber].SetPointer = Find(TwoCityNumber);
}
City[OneCityNumber].CountInSet += City[TwoCityNumber].CountInSet;
}

int Find (int CityNumber ) {
int i,List[100],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);
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
69
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;
char NameVar [80];
char FromCity[80];
char Dummy[80];
char ToCity[80];
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);
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
70
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);
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++;
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
71
EdgePos++;
}
DumpCities();
DumpTree();
}
}


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[250][4]; //edges in the graph
int g; //no of edges in the graph
int tree_edge[250][4]; //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[50],t1; // Set 1
int T2[50],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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
72
cin>>w;
if(w!=0)
{
g++;
graph_edge[g][1]=i;
graph_edge[g][2]=j;
graph_edge[g][3]=w;
}
}
}
// print the graph edges
cout<<\n\nThe edges in the given graph are::\n;
for(i=1;i<=g;i++)
cout<< < <<graph_edge[i][1]
<< , <<graph_edge[i][2]
<< > ::<<graph_edge[i][3]<<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]=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
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
73
int min=9999;
int p;
int u,v,w;
for(i=1;i<=g;i++)
{
bool flag1=false,flag2=false;
//if u and v are in different sets
if(findset(graph_edge[i][1])!=findset(graph_edge[i][2]))
{
if(min>graph_edge[i][3])
{
min=graph_edge[i][3];
u=graph_edge[i][1];
v=graph_edge[i][2];
w=graph_edge[i][3];
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][1]=graph_edge[l+1][1];
graph_edge[l][2]=graph_edge[l+1][2];
graph_edge[l][3]=graph_edge[l+1][3];
}
g;
//add the edge to the tree
t++;
tree_edge[t][1]=u;
tree_edge[t][2]=v;
tree_edge[t][3]=w;
//Alter the set partitions
t1++;
int m;
if(findset(v)==2)
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
74
T1[t1]=v;
m=v;
}
else if(findset(u)==2)
{
T1[t1]=u;
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][1]
<< , <<graph_edge[i][2]
<< > ::<<graph_edge[i][3]<<endl;
cout<<endl<<endl;}}
void prims::output()
{
cout<<\nThe selected edges are ::\n;
for(int i=1;i<=t;i++)
cout<< < <<tree_edge[i][1]
<< , <<tree_edge[i][2]
<< > ::<<tree_edge[i][3]<<endl;
}
int main(){
prims obj;
obj.input();
obj.algorithm();obj.output();return 0;
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
75



DICTIONARIES

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








www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
76
13.Write a C++ program to implement all the functions of a dictionary (ADT) using
hashing.

Open hashing
#include<iostream.h>
#include<conio.h>
#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)
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
77
{
ht[i]->data=0;
ht[i]->next=newnode;
}
else
{

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;

www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
78
flag=1;
}
else
{
temp=ht[i]->next;
while(temp!=0)
{
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
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
79

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class symboltable
{
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;
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
80
} }
while (j!=i);
}
}
void symboltable::search(int x)
{
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";
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Data Structures Through C++ Lab LAB MANUAL
R.V Ramana Chary Department Of IT BVRIT
81
cin>>n;
switch(n)
{
case 1:
cout<<"enter ele to insert :..";
cin>>x;
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);
}}}









www.jntuworld.com
www.jntuworld.com
www.jwjobs.net

You might also like