8/10/2019 Data Structure throuh cpp lab manual.pdf
1/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 1
1. Write C++ programs to implement the following using an array.a) Stack ADT
b) Queue ADT
2. Write C++ programs to implement the following using a singly linked list.
a) Stack ADTb) Queue ADT
3. Write C++ program to implement the deque (double ended queue) ADT usinga 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 givenbinary tree in
a) Preorderb) inorder andc) 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 sortc) Heap sort
9. Write a C++ program to perform the following operationsa) Insertion into a B-tree
b) Deletion from a B-tree
10. Write a C++ program to perform the following operationsa) Insertion into an AVL-treeb) Deletion from an AVL-tree
11. Write a C++ program to implement Kruskals algorithm to generate a minimumspanning tree.
12. Write a C++ program to implement Prims algorithm to generate a minimumspanning tree.
13. Write a C++ program to implement all the functions of a dictionary (ADT) usinghashing.
Templates
8/10/2019 Data Structure throuh cpp lab manual.pdf
2/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 2
Template FunctionsSuppose we want to write a function that finds the maximum of two objects. To find themaximum 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;
elsereturn b;
}and so on. You can imagine that we would have to write a separate function for everydata type (chars, strings, dates, etc.), but notice that the body of each function is exactlythe same!!!
Template Function DefinitionThe definition of a template function depends on an underlying data type.For example:
template 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 thatwill 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 argumentsand at that point determines the data type of Item.
Using Template FunctionsTemplate functions are used (called) in exactly the same way as regular functions. Forexample, if we want to output the maximum of the integers 1000 and 2000, we wouldwrite:
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
3/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 3
string s1("foo");string s2("bar");cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
4/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 4
One of the most common forms of data organization in computer programs is theordered or linear list, which is often written as a = (a1, a2, .., an). A stack is an orderedlist in which all insertions and deletions are made at one end, called the top. A queue isan ordered list in which all insertions take place at one end, the rear, whereas alldeletions 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 astack, in that order, then the first element to be removed must be E. Equivalently we saythat the last element to be inserted into the stack is the first to be removed. For thisreason stacks are sometimes referred to as Last In First Out (LIFO) lists. The operationsof 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 fiveelements 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 elementin the stack is stored at stack[0], the second at stack[1], and ith at stack[i-1]. Associatedwith the array is a variable, typically called top, which points to the top element, to testwhether the stack is empty, we ask if (top
8/10/2019 Data Structure throuh cpp lab manual.pdf
5/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 5
public:stack();void push(T);T pop();void display();};
template stack::stack(){top=-1;}template void stack::push(T n){if(top==max-1) cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
6/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 6
{cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
7/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 7
public:queue();void insert(T);T remove();void display();};
template queue::queue(){front=0;rear=-1;}template void queue::insert(T n){if(rear==max-1) cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
8/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 8
do{cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
9/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 9
2).Write C++ programs to implement the following using a singly linked list.a) Stack ADT#include#include
template class stack{
struct node{
T data;node *link;
}* top;public:
stack();void push(T);T pop();
void display();~stack();
};template stack::stack(){
top=0;}template void stack:: push(T x){
node *p=new node;p->data=x;p->link=top;top=p;
}template T stack::pop(){
node *temp=top;top=top->link;T x=temp->data;delete temp;
return x;}template void stack::display(){
if(top==0)cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
10/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 10
node* temp=top;while(temp!=0){
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
11/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 11
r=st.pop();if(r==-1)
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
12/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 12
b) Queue ADT
#include #include template
struct node{T data;node *link;
};template class queue{
node *f,*r;public:
queue();void insert(T);
T del();void display();T first();T last();
};template queue::queue(){
f=0;r=0;
}template void queue :: insert(T x){
node *p=new node;p->data=x;p->link=0;if(f==0){
f=p;r=p;
}else
{ r->link=p;r=p;
}}template T queue::del(){
if(f==0)
8/10/2019 Data Structure throuh cpp lab manual.pdf
13/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 13
return -1;else{
node *temp=f;T x=temp->data;f=f->link;
return x;}}template void queue ::display(){
if(f==0)cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
14/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 14
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
15/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 15
}}
void main(){
clrscr();
int ch;menu1();cin>>ch;if(ch
8/10/2019 Data Structure throuh cpp lab manual.pdf
16/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 16
Doubly Linked ListsOne shortcoming of singly linked list is we can only move forwards through the list. Adoubly 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 ateither end i.e., deque supports insertion and deletion from the front and back.
The Deque Abstract Data TypeinsertFirst(e): Insert e at the beginning of deque.insertLast(e): Insert e at end of dequeremoveFirst(): Removes and returns first elementremoveLast(): Removes and returns last element
Additionally supported methods include:
To Implement Deque with Doubly Linked Lists we use a doubly linked list with specialheader and trailer nodes
When implementing a doubly linked list, we add two special nodes to the ends of thelists: the header and trailer nodes.
The headernode goes before the first list element. It has a valid next link but anull prev link.
The trailernode goes after the last element. It has a valid prev reference but anull next reference.
NOTE: the header and trailer nodes are sentinel or dummy nodes because they donot store elements. Heres a diagram of our doubly linked list:
8/10/2019 Data Structure throuh cpp lab manual.pdf
17/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 17
03.Write C++ program to implement the deque (double ended queue) ADT
using
a doubly linked list.
#include#include#include
class node{
public:int data;class node *next;class node *prev;};
class dqueue: public node{node *head,*tail; int top1,top2; public: dqueue() { top1=0; top2=0; head=NULL; tail=NULL; } void push(int x){node *temp;int ch;if(top1+top2 >=5){ cout next=NULL; head->prev=NULL; tail=head; top1++; }else{
8/10/2019 Data Structure throuh cpp lab manual.pdf
18/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 18
cout ch;
if(ch==1) {
top1++; temp=new node; temp->data=x; temp->next=head; temp->prev=NULL; head->prev=temp; head=temp; } else { top2++; temp=new node;
temp->data=x; temp->next=NULL; temp->prev=tail; tail->next=temp; tail=temp; }
} }void pop() { int ch; cout ch; if(top1 + top2 prev; tail->next=NULL; } }
8/10/2019 Data Structure throuh cpp lab manual.pdf
19/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 19
void display() { int ch;
node *temp; cout ch; if(top1+top2
8/10/2019 Data Structure throuh cpp lab manual.pdf
20/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 20
d1.push(x); break; case 2: d1.pop(); break; case 3: d1.display(); break; case 4: exit(1); } }while(1);
}
4. Write a C++ program to perform the following operations:
a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.
5.Write C++ programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.
TREES
A tree is a finite set of one or more nodes such that there is a specially designated nodecalled the root and the remaining nodes are partitioned into n0 disjoint sets T1, .,Tn,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 nodesthat is either empty or consists of a root and two disjoint binary trees called the left andright subtrees.
ADT of binary tree
AbstractDataType binaryTree{instances
collection of elements; if not empty, the collection is partitioned into a root, leftsubtree, and right subtree; each subtree is also a binary tree;
operationsempty( ) : 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 functionto use;
inorder(visit) : inorder traversal of a binary tree
8/10/2019 Data Structure throuh cpp lab manual.pdf
21/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 21
postorder(visit): postorder traversal of a binary tree.
}
Algorithms for non-recursive tree traversals.
Preorder traversal
1. define a stack2. 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 stack2. 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 stack2. 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 satisfiesthe 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
8/10/2019 Data Structure throuh cpp lab manual.pdf
22/84
8/10/2019 Data Structure throuh cpp lab manual.pdf
23/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 23
nodeptr findmin(nodeptr);nodeptr findmax(nodeptr);void copy(nodeptr &,nodeptr &);void makeempty(nodeptr &);nodeptr nodecopy(nodeptr &);void preorder(nodeptr);
void inorder(nodeptr);void postorder(nodeptr);void preordernr(nodeptr);void inordernr(nodeptr);void postordernr(nodeptr);void leftchild(int,nodeptr &);void rightchild(int,nodeptr &);
};
void bstree::insert(int x,nodeptr &p)
{if (p==NULL){
p = new node;p->ele=x;p->left=NULL;p->right=NULL;
}else{
if (x < p->ele)insert(x,p->left);
else if (x>p->ele)insert(x,p->right);
elsecoutele)del(x,p->right);
else if ((p->left == NULL) && (p->right ==NULL)){
d=p;free(d);
8/10/2019 Data Structure throuh cpp lab manual.pdf
24/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 24
p=NULL;}else if (p->left == NULL)
{d=p;free(d);
p=p->right;}else if (p->right ==NULL){
d=p;p=p->left;free(d);
}else
p->ele=deletemin(p->right);}
int bstree::deletemin(nodeptr &p){
int c;if (p->left == NULL){
c=p->ele;p=p->right;return c;
}else
c=deletemin(p->left);return c;
}
void bstree::copy(nodeptr &p,nodeptr &p1){
makeempty(p1);p1=nodecopy(p);
}
void bstree::makeempty(nodeptr &p){
nodeptr d;
if (p!=NULL){makeempty(p->left);makeempty(p->right);d=p;free(d);
p=NULL;}
}
8/10/2019 Data Structure throuh cpp lab manual.pdf
25/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 25
nodeptr bstree::nodecopy(nodeptr &p){
nodeptr temp;if (p == NULL)
return p;
else{temp = new node;temp->ele=p->ele;temp->left = nodecopy(p->left);temp->right = nodecopy(p->right);return temp;
}}
nodeptr bstree::findmin(nodeptr p)
{if (p==NULL){
coutleft;
return p;}
}
nodeptr bstree::findmax(nodeptr p){
if (p==NULL){
coutright;return p;
}}
void bstree::find(int x,nodeptr &p)
8/10/2019 Data Structure throuh cpp lab manual.pdf
26/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 26
{if (p==NULL)
cout p->ele)find(x,p->right);
elsecoutright);cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
27/84
8/10/2019 Data Structure throuh cpp lab manual.pdf
28/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 28
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
29/84
8/10/2019 Data Structure throuh cpp lab manual.pdf
30/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 30
case 10:cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
31/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 31
6.Write C++ programs that use non-recursive functions to traverse the given
binary tree in
a) Preorder
b) inorder and
c) postorder.
# include # include # include # include
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;
8/10/2019 Data Structure throuh cpp lab manual.pdf
32/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 32
delete temp;}
}
nodeptr topele(){
if (top !=NULL)return top->ele;else
return NULL;}
int isempty(){return ((top == NULL) ? 1 : 0);}
};
class bstree{
public:void insert(int,nodeptr &);void del(int,nodeptr &);int deletemin(nodeptr &p)void preorder(nodeptr);void inorder(nodeptr);void postorder(nodeptr);void preordernr(nodeptr);void inordernr(nodeptr);void postordernr(nodeptr);
};
void bstree::insert(int x,nodeptr &p){
if (p==NULL){
p = new node;
p->ele=x;p->left=NULL;p->right=NULL;
}else{
if (x < p->ele)insert(x,p->left);
else if (x>p->ele)
8/10/2019 Data Structure throuh cpp lab manual.pdf
33/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 33
insert(x,p->right);else
coutele)
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;
}
8/10/2019 Data Structure throuh cpp lab manual.pdf
34/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 34
void bstree::preorder(nodeptr p){
if (p!=NULL){
coutright);}}void bstree::inorder(nodeptr p){
if (p!=NULL){
inorder(p->left);coutleft);postorder(p->right);cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
35/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 35
s.pop();}}
}
void bstree::inordernr(nodeptr p)
{ stack s;while (1){if (p != NULL){
s.push(p);p=p->left;
}else{if (s.isempty())
{cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
36/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 36
}elseif (s.topele()->right == NULL){
p=s.topele();s.pop();
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
37/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 37
case 2:cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
38/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 38
exit(0);}coutc;}while (c=='y' || c == 'Y');return 0;
}
GRAPHS
A graph can be thought of a collection of vertices (V) and edges (E), so wewrite,
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 directedgraphs)
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. Allunvisited 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 andor put on to the end of a list of unexplored list of vertices. The first vertex on this list isthe next to be explored. Exploration continues until no unexplored vertex is left. The listof unexplored vertices operates as a queue and can be represented using any of thestandard queue representations.
8/10/2019 Data Structure throuh cpp lab manual.pdf
39/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 39
Algorithm BFS(v)
//A breadth first search of G is carried out beginning at vertex v. For
//any node I, visited[I=1 if I has already been visited. The graph G
//and array visited are global; visited[] is initialized to zero.
{
u:=v; //q is a queue of unexplored verticesvisited[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 vertexdelete 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 explorationof a vertex v is suspended as soon as a new vertex is reached. At this time of explorationof the new vertex u begins. When this new vertex has been explored, the exploration ofv 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. Thisinterpretation is that the set t of edges so far selected for the spanning tree be such that itis possible to complete t into a tree. Thus t may not be a tree at all stages of algorithm.
8/10/2019 Data Structure throuh cpp lab manual.pdf
40/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 40
7.Write a C++ programs for the implementation of bfs and dfs for a given
graph.
#include#include#include
void create(); // For creating a graphvoid 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>choice; switch(choice) {
case 1: dfs(); break;case 2: bfs();
8/10/2019 Data Structure throuh cpp lab manual.pdf
41/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 41
break;case 3: exit(0); break;default:
coutdata=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
8/10/2019 Data Structure throuh cpp lab manual.pdf
42/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 42
if(dat==0) break;k=new link;k->adj=NULL;if(flag==0){
p->adj=k; l=k; flag++;}else{
l->adj=k; l=k;}q=start;while(q!=NULL){
if(q->data==dat) k->next=q; q=q->next;}
} p=p->next; } coutstatus=0; p=p->next;
} p=start; qu[0]=p->data; p->status=1; while(1) { if(qu[j]==0)
break; p=start;
8/10/2019 Data Structure throuh cpp lab manual.pdf
43/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 43
while(p!=NULL) {
if(p->data==qu[j]) break;p=p->next;
}
k=p->adj; while(k!=NULL) {
q=k->next;if(q->status==0){
qu[i]=q->data; q->status=1; qu[i+1]=0; i++;}k=k->adj;
} j++; } j=0; cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
44/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 44
p=start; while(p!=NULL) { p->status=0; p=p->next; }
p=start; stack[0]=0; stack[top]=p->data; p->status=1; while(1) { if(stack[top]==0)
break; p=start; while(p!=NULL) {
if(p->data==stack[top])
break;p=p->next;
} coutdata; q->status=1;}k=k->adj;
} } getch(); return;}
8/10/2019 Data Structure throuh cpp lab manual.pdf
45/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 45
SORTING METHODS
HEAP SORT
The best-known example of the use of a heap arises in its application to sorting. A
conceptually simple sorting strategy has been given before, in which the maximumvalue is continually removed from the remaining unsorted elements. A sortingalgorithm that incorporates the fact that n elements can be inserted I O(n) time is givenin 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);
}}
QUICK SORT
In quick sort, the division into two subarrays is made so that the sorted subarrays do noneed 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. Therearrangement of the elements is accomplished by picking some element of a[], sayt=a[s], and then reordering the other elements so that all elements appearing before t ina[1:n] are less than or equal to t and all elements appearing after t are greater than orequal 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 nondecreasingorder. Given a sequence of n elements, the idea is to imagine them split into two setsa[1] to a[n/2] and a[n/2 +1] to a[n]. Each set is individually sorted, and the resultingsorted sequences are merged to produce a single sorted sequence of n elements.
8/10/2019 Data Structure throuh cpp lab manual.pdf
46/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 46
8.Write C++ programs for implementing the following sorting methods:
a) Merge Sort
#include
#includeusing namespace std;void mergesort(int *,int,int);void merge(int *,int,int,int);int a[20],i,n,b[20];
main(){cout n;cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
47/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 47
}
if( h > mid) for(k=j;k
8/10/2019 Data Structure throuh cpp lab manual.pdf
48/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 48
elsecoutarr[1])
j=2;while(j>=0&&temp
8/10/2019 Data Structure throuh cpp lab manual.pdf
49/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 49
{for(int i=0;i
8/10/2019 Data Structure throuh cpp lab manual.pdf
50/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 50
B-trees are especially useful for trees stored on disks, since their height, and hence alsothe number of disk accesses, can be kept small.
The growth and contraction of m-way search trees occur at the leaves. On the otherhand, 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 atthe location of the submitted key.
add 19
add 21
8/10/2019 Data Structure throuh cpp lab manual.pdf
51/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 51
Deletions
Key that is to be removed from a node with non-empty subtrees is beingreplaced with the largest key of the left subtree or the smallest key in the rightsubtree. (The replacement is guaranteed to come from a leaf.)
8/10/2019 Data Structure throuh cpp lab manual.pdf
52/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 52
remove 26
If a node becomes under staffed, it looks for a sibling with an extra key. If sucha sibling exist, the node takes a key from the parent, and the parent gets the extrakey from the sibling.
remove 22
8/10/2019 Data Structure throuh cpp lab manual.pdf
53/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 53
If a node becomes under staffed, and it cant receive a key from a sibling, thenode is merged with a sibling and a key from the parent is moved down to thenode.
8/10/2019 Data Structure throuh cpp lab manual.pdf
54/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 54
remove 18
10.Write a C++ program to perform the following operationsa) Insertion into an AVL-treeb) Deletion from an AVL-tree
8/10/2019 Data Structure throuh cpp lab manual.pdf
55/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 55
AVL Trees
An AVL tree (also called an "admissible tree") is a tree in which the height of the left
and right subtrees of every node differ by at most one - referred to as "height-balanced".
Example AVL trees:3 6 5
/ \ / \ / \ 2 5 4 7 2 9 / / \ / \ 3 1 4 7 12 / \ / \ 3 8 11 14 / 10
Example non-AVL trees:5 6 5
/ / \ / \ 3 3 10 2 9 / / \ / / \ / \2 1 4 7 1 4 7 12
\ / / \ 8 3 11 14 / 10In order to indicate the differences between the heights of the right and left subtrees of agiven (root) node, a balance factor is defined for that node of the subtree.
We define the balance factor, BF:BF = (height of right subtree - height of left subtree)
So, BF = -1, 0 or +1 for an AVL tree.Balance factors for example AVL trees (node key values not shown):
0 -1 +1 / \ / \ / \ 0 0 -1 0 -1 -1
/ / / \ 0 0 +1 0 \
0When 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 isunbalanced 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 T3represent subtrees (a node was added to T1 which made B leftheavy and unbalanced A).
A SRR at A B
8/10/2019 Data Structure throuh cpp lab manual.pdf
56/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 56
/ \ ----------> / \ B T3 T1 A / \ / \ T1 T2 T2 T3Single 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 T3represent subtrees (a node was added to T3 which made B right-heavy and unbalancedA).
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 isunbalanced 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 atnode 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 T2That is, DLR equiv SLR + SRR
Double Right Rotation (DRR):A is the node that the rotation is performed on. This rotation is performed when A isunbalanced 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
8/10/2019 Data Structure throuh cpp lab manual.pdf
57/84
8/10/2019 Data Structure throuh cpp lab manual.pdf
58/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 58
Insertion into an AVL tree may be carried out by inserting the given value into the treeas if it were an unbalanced binary search tree, and then retracing one's steps toward theroot, rotating about any nodes which have become unbalanced during the insertion.
DeletionDeletion from an AVL tree may be carried out by rotating the node to be deleted downinto a leaf node, and then pruning off that leaf node directly. Since at most log n nodesare 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 #include #include #include #include
#include #include
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);
8/10/2019 Data Structure throuh cpp lab manual.pdf
59/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 59
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 {
if (xelement){ insert(x,p->left); //GDisplay(root,midx,50); if ((bsheight(p->left) - bsheight(p->right))==2) {
8/10/2019 Data Structure throuh cpp lab manual.pdf
60/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 60
if (x < p->left->element)p = singlerotateleft(p); //single rotation left
elsep = 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
elsep = 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){
8/10/2019 Data Structure throuh cpp lab manual.pdf
61/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 61
gotoxy(4,21); printf("Empty Tree"); return p;}else{ while(p->right !=NULL)
p=p->right; return p;}
}
void find(int x,nodeptr &p){
if (p==NULL){ gotoxy(4,21); printf("Element not found");}
else if (x < p->element) find(x,p->left);else if (x>p->element) find(x,p->right);else{ gotoxy(4,21); printf("Element found !");}
}
void del(int x,nodeptr &p){
nodeptr d;if (p==NULL){ gotoxy(4,21); printf("Element not found");}else if ( x < p->element){ del(x,p->left); if ((bsheight(p->left) - bsheight(p->right))==2)
{ if (x < p->left->element)p = singlerotateleft(p); //single rotation left
elsep = doublerotateleft(p); //double rotation left
}}else if (x > p->element){
8/10/2019 Data Structure throuh cpp lab manual.pdf
62/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 62
del(x,p->right); if ((bsheight(p->right) - bsheight(p->left))==2) { if (x > p->right->element)
p = singlerotateright(p); //single rotation right else
p = doublerotateright(p); //double rotation right }}else if ((p->left == NULL) && (p->right == NULL)){ d=p; free(d); p=NULL; gotoxy(4,21); printf("Element deleted !");}else if (p->left == NULL){
d=p; free(d); p=p->right; gotoxy(4,21); printf("Element deleted !");}else if (p->right == NULL){ d=p; p=p->left; free(d); gotoxy(4,21); printf("Element deleted !");}else p->element = deletemin(p->right);
}
int deletemin(nodeptr &p){
int c;gotoxy(4,21); printf("deltemin");if (p->left == NULL){ c=p->element;
p=p->right; return c;}else{ c=deletemin(p->left); return c;}
}
8/10/2019 Data Structure throuh cpp lab manual.pdf
63/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 63
void preorder(nodeptr p){
if (p!=NULL){ printf("%d-->",p->element);
preorder(p->left); preorder(p->right);}
}
void inorder(nodeptr p){
if (p!=NULL){ inorder(p->left); printf("%d-->",p->element); inorder(p->right);
}}
void postorder(nodeptr p){
if (p!=NULL){ postorder(p->left); postorder(p->right); printf("%d-->",p->element);}
}
int max(int value1, int value2){
if(value1 > value2) return value1;else return value2;
}
int bsheight(nodeptr p){
int t;if (p == NULL)return -1;
else{
t = p->height;return t;
}}
8/10/2019 Data Structure throuh cpp lab manual.pdf
64/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 64
nodeptr singlerotateleft(nodeptr &p1){
nodeptr p2;p2 = p1->left;p1->left = p2->right;
p2->right = p1;p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;p2->height = max(bsheight(p2->left),p1->height) + 1;return p2;
}
nodeptr singlerotateright(nodeptr &p1){
nodeptr p2;p2 = p1->right;p1->right = p2->left;p2->left = p1;
p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;p2->height = max(p1->height,bsheight(p2->right)) + 1;return p2;
}
nodeptr doublerotateleft(nodeptr &p1){
p1->left = singlerotateright(p1->left);return singlerotateleft(p1);
}
nodeptr doublerotateright(nodeptr &p1){
p1->right = singlerotateleft(p1->right);return singlerotateright(p1);
}
int count=0;int nonodes(nodeptr p){
if (p!=NULL){
nonodes(p->left);
nonodes(p->right);count++;}return count;
}
void twolinebox(int x1,int y1,int x2,int y2){int x,y;textcolor(WHITE);
8/10/2019 Data Structure throuh cpp lab manual.pdf
65/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 65
gotoxy(x1,y1); cprintf(""); //201gotoxy(x2,y1); cprintf(""); //187
for(y=y1+1;y=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);
8/10/2019 Data Structure throuh cpp lab manual.pdf
66/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 66
twolinebox(1,1,80,24);center(1,YELLOW,"[Adelson-Velskii and Landis Tree]");cprintxy(20,3,GREEN,"[A]- Insertion");cprintxy(20,4,GREEN,"[B]- Find Minimum");cprintxy(20,5,GREEN,"[C]- Find Maximum");cprintxy(20,6,GREEN,"[D]- Search Node");
cprintxy(20,7,GREEN,"[E]- Display Tree");cprintxy(43,3,GREEN,"[F]- Delete Node");cprintxy(43,4,GREEN,"[G]- Preorder");cprintxy(43,5,GREEN,"[H]- Inorder");cprintxy(43,6,GREEN,"[I]- Postorder");cprintxy(43,7,GREEN,"[J]- Height");cprintxy(20,9,GREEN,"[any key]- Quit...");
cprintxy(20,11,LIGHTRED,"Enter your choice: ");}
void main()
{
nodeptr root,min,max;int a,findele,delele,leftele,rightele,flag;char choice,value[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...");
cprintxy(20,11,LIGHTRED,"Enter your choice:\>");choice=getch();switch(toupper(choice)){
8/10/2019 Data Structure throuh cpp lab manual.pdf
67/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 67
case 'A':do{
gotoxy(4,14); printf("Enter node value: ");a=atoi(gets(value));if(atoi(value)==0)
{ gotoxy(4,21); printf("Error!!! Enter a valid integervalue only.");
gotoxy(4,22); printf("Press any key tocontinue...");
getch();}}while(atoi(value)==0);insert(a,root);gotoxy(4,15);inorder(root);/*
initgraph(&gdriver,&gmode,"c:\tc\bgi");errorcode = graphresult();maxx=getmaxx();midx=maxx/2,xcoord=midx/2,ycoord=40;if (errorcode != grOk){
printf("Graphics error: %s", grapherrormsg(errorcode));
printf("Press any key to stop"); getch(); exit(1);}cleardevice();GDisplay(root,midx,50);getch();restorecrtmode();*/
break;case 'B':
if (root !=NULL){min=findmin(root);gotoxy(4,14); printf("Min element : %d",min->element);
}break;case 'C':
if (root !=NULL){max=findmax(root);gotoxy(4,14); printf("Max element : %d",max->element);}
break;
8/10/2019 Data Structure throuh cpp lab manual.pdf
68/84
8/10/2019 Data Structure throuh cpp lab manual.pdf
69/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 69
midx=maxx/2,xcoord=midx/2,ycoord=40;if (errorcode != grOk){
printf("Graphics error: %s", grapherrormsg(errorcode));
printf("Press any key to stop");
getch(); exit(1);}
cleardevice();setbkcolor(LIGHTBLUE);settextstyle(2,0,5);outtextxy(20,10,"Adelson-Velskii and Landis Tree");GDisplay(root,midx,50);getch();restorecrtmode();
break;
case 'G':gotoxy(4,14); printf(" Preorder Printing...");gotoxy(4,15);
preorder(root);break;
case 'H':gotoxy(4,14); printf(" Inorder Printing...");gotoxy(4,15);inorder(root);
break;
case 'I':gotoxy(4,14); printf(" Postorder Printing...");gotoxy(4,15);
postorder(root);break;
case 'J':gotoxy(4,14); printf(" Height and Depth:
%d",bsheight(root));gotoxy(4,15); printf("No. of nodes: %d",nonodes(root));
break;}
gotoxy(4,22); printf(" Do you want to continue (y/n)?");ch=toupper(getch());}while(ch!='N');
}
11.Write a C++ program to implement Kruskals algorithm to generate a minimumspanning tree.
8/10/2019 Data Structure throuh cpp lab manual.pdf
70/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 70
#include 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 City[TwoCityNumber].CountInSet) { City[TwoCityNumber].SetPointer = Find(OneCityNumber); } else {
8/10/2019 Data Structure throuh cpp lab manual.pdf
71/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 71
City[OneCityNumber].SetPointer = Find(TwoCityNumber); } City[OneCityNumber].CountInSet += City[TwoCityNumber].CountInSet;}
int Find (int CityNumber ) {
int i,List[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
8/10/2019 Data Structure throuh cpp lab manual.pdf
72/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 72
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);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);
8/10/2019 Data Structure throuh cpp lab manual.pdf
73/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 73
if (FoundFlag) { ToCityIndex = GetCityIndex(ToCity ,&FoundFlag); if (FoundFlag) { Edge[EdgeCount].v = FromCityIndex; Edge[EdgeCount].w = ToCityIndex; Edge[EdgeCount].length = Mileage;
EdgeCount++; } } if (!FoundFlag) { printf( "City Not found in %s , %s \n",FromCity,ToCity); }
fgets(NameVar,sizeof(NameVar),edge); CleanString(NameVar);}
// insertion sort the edges; of course, we would be better using an O(N Log N) sort
for (i=0;i
8/10/2019 Data Structure throuh cpp lab manual.pdf
74/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 74
12.Write a C++ program to implement Prims algorithm to generate a minimumspanning tree.
#include
class prims
{private:int n; //no of nodesint graph_edge[250][4]; //edges in the graphint g; //no of edges in the graphint tree_edge[250][4]; //edges in the treeint t; //no of edges in the treeint s; //source node
//Partition the graph in to two setsint T1[50],t1; // Set 1int T2[50],t2; // Set 2
public:void input();int findset(int);void algorithm();void output();};void prims::input(){cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
75/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 75
}}}
// print the graph edges
cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
76/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 76
//if u and v are in different setsif(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
8/10/2019 Data Structure throuh cpp lab manual.pdf
77/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 77
m=u;}
int x;for(x=1;T2[x]!=m;x++);
for(;x
8/10/2019 Data Structure throuh cpp lab manual.pdf
78/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 78
A dictionary is a collection of Pairs of the form (k,v) where k is a key and v is the valueassociated 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 keysoperations
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 asstudents registered for the course. When a new student registers, a pair/recordcorresponding to this student is inserted into the dictionary; when a student drops thecourse, her record may be deleted. The student name may be used as the key; theremaining information in a record is the value associated with the key.
A Dictionary may be maintained as an ordered linear list and can be representedusing skip lists. Another possibility for the representation of a dictionary is to usehashing. This method uses a hash function to map dictionary pairs into positions in atable called the hash table. In the ideal situation, if pair p has the key k and f is the hashfunction, then p is stored in position f(k) of the table. Assume for now that each positionof 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 thedesired pair. If not, the dictionary contains no pair with the specified key k. in theformer case the pair may be deleted by making position f(k) of the table empty. In thelatter case the pair may be inserted by placing it in position f(k).
13.Write a C++ program to implement all the functions of a dictionary (ADT) usinghashing.
Open hashing#include#include
8/10/2019 Data Structure throuh cpp lab manual.pdf
79/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 79
#includestruct 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;inext=0;}}void symbtable::insert(int x){int i=hashfun(x);node *newnode,*last;newnode= new node;
newnode->data=x;newnode->next=0;if(ht[i]->data==0){ht[i]->data=0;ht[i]->next=newnode;}else{
8/10/2019 Data Structure throuh cpp lab manual.pdf
80/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 80
last=ht[i]->next;while(last->next!=0){last=last->next;}
last->next=newnode;}}
void symbtable::disp(){node *temp,*last;for(int i=0;i
8/10/2019 Data Structure throuh cpp lab manual.pdf
81/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 81
{if(temp->data==x){cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
82/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 82
int buckets;int *ht;
public:symboltable(int s){buckets =s;
ht= new int[buckets];}void init();void dis();int hashfun(int);void search(int );void insert(int);};void symboltable::init(){for(int i=0;i
8/10/2019 Data Structure throuh cpp lab manual.pdf
83/84
Data Structures Through C++ Lab LAB MANUAL
vidya vikas Institute of technology 83
int i=hashfun(x);int flag=0;int j;if(ht[i]==x){cout
8/10/2019 Data Structure throuh cpp lab manual.pdf
84/84
Data Structures Through C++ Lab LAB MANUAL
s.insert(x);break;case 2:coutx;s.search(x);
break;case 3:s.dis();
break;case 4:exit(1);}}}