Sie sind auf Seite 1von 53

Mahatma Gandhi University College of Engineering & Technology

Data Structures Through C++ Lab Programs

*************************************************************************************

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[100];
int top;
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>

SAGAR M DEPARTMENT OF CSE Page 1


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 2


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

b) 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[100];
int front,rear;
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)

SAGAR M DEPARTMENT OF CSE Page 3


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 4


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

break;
case 4:exit(0);
default: cout<<"invalid choice";
}
}while(1);
}

*************************************************************************************
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()
{

SAGAR M DEPARTMENT OF CSE Page 5


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 6


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 7


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

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

SAGAR M DEPARTMENT OF CSE Page 8


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 9


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 10


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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;
if(ch<4)

SAGAR M DEPARTMENT OF CSE Page 11


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

*************************************************************************************
3. 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.
*************************************************************************************
4.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 n.0 disjoint sets T1, ….,Tn,
where each of these sets is a tree. The sets are called the subtrees of the root.

SAGAR M DEPARTMENT OF CSE Page 12


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

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

SAGAR M DEPARTMENT OF CSE Page 13


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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


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.

# include <conio.h>
# include <process.h>

SAGAR M DEPARTMENT OF CSE Page 14


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 15


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 16


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 17


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 18


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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 )
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 node does 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 !";
}

SAGAR M DEPARTMENT OF CSE Page 19


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 20


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 21


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

cout<<" 9.Postorder ";


if (root==NULL)
cout<<"Tree is empty";
else
{
cout<<"Postorder traversal (Recursive) is : ";
bst.postorder(root);
}
break;
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;
}

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

SAGAR M DEPARTMENT OF CSE Page 22


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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;
delete temp;
}
}
nodeptr topele()

SAGAR M DEPARTMENT OF CSE Page 23


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

{
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)
insert(x,p->right);
else
cout<<"Element already Exits !";
}
}
void bstree:: del(int x,nodeptr &p)
{
nodeptr d;

SAGAR M DEPARTMENT OF CSE Page 24


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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;
}
void bstree::preorder(nodeptr p)
{
if (p!=NULL)
{
cout<<p->ele<<"-->";
preorder(p->left);

SAGAR M DEPARTMENT OF CSE Page 25


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 26


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 27


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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;
case 2:

SAGAR M DEPARTMENT OF CSE Page 28


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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:
exit(0);
}
cout<<" \n Continue (y/n) ? ";

SAGAR M DEPARTMENT OF CSE Page 29


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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.

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

SAGAR M DEPARTMENT OF CSE Page 30


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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.

Kruskal’s 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.

Write a C++ programs for the implementation of bfs and dfs for a given graph.

SAGAR M DEPARTMENT OF CSE Page 31


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

#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 // 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();

SAGAR M DEPARTMENT OF CSE Page 32


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 33


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 34


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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[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;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;

SAGAR M DEPARTMENT OF CSE Page 35


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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
{
t:=a[i];
a[i]:=a[1];
a[1]:=t;
adjust(a,1,i-1);

SAGAR M DEPARTMENT OF CSE Page 36


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

}
}

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.

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[20],i,n,b[20];
main()
{
cout <<"\n enter no of elements";
cin >> n;
cout <<"enter the elements";
for(i=0;i<n;i++)
cin >> a[i];
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)
{

SAGAR M DEPARTMENT OF CSE Page 37


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 38


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 39


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

{
T temp=arr[i];
arr[i]=arr[0];
int k=0;
int j;
if(i==1)
j=-1;
else
j=1;
if(i>2&&arr[2]>arr[1])
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()

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

SAGAR M DEPARTMENT OF CSE Page 40


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

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.

add 19
add 21
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.)

Write a C++ program to perform the following operations


a) Insertion into an AVL-tree
b) Deletion from an AVL-tree

SAGAR M DEPARTMENT OF CSE Page 41


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 42


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

{
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)
{
if (x < p->left->element)
p = singlerotateleft(p); //single rotation left
else
p = doublerotateleft(p); //double rotation left

SAGAR M DEPARTMENT OF CSE Page 43


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

}
}
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)
{
gotoxy(4,21); printf("Empty Tree");
return p;

SAGAR M DEPARTMENT OF CSE Page 44


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

}
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)
{

SAGAR M DEPARTMENT OF CSE Page 45


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 46


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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)
return -1;
else
{
t = p->height;
return t;

SAGAR M DEPARTMENT OF CSE Page 47


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 48


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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);
twolinebox(1,1,80,24);

SAGAR M DEPARTMENT OF CSE Page 49


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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");
cprintxy(43,7,GREEN,"[J]-Height");
cprintxy(20,9,GREEN,"[any key]-Quit...");

SAGAR M DEPARTMENT OF CSE Page 50


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 51


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 52


Mahatma Gandhi University College of Engineering & Technology
Data Structures Through C++ Lab Programs

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

SAGAR M DEPARTMENT OF CSE Page 53

Das könnte Ihnen auch gefallen