0% found this document useful (0 votes)
45 views98 pages

Practical Solution - 230426 - 131012

The document describes a C program that implements various binary search tree (BST) operations including: - Create/build a BST from a list of numbers - Perform recursive inorder, preorder, and postorder traversals of the BST - Insert new nodes into the BST - Delete nodes from the BST - Copy an existing BST to create a new mirrored/reflected tree - Count the total, leaf, and non-leaf nodes in the BST The program allows the user to select which BST operation to perform and outputs the results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views98 pages

Practical Solution - 230426 - 131012

The document describes a C program that implements various binary search tree (BST) operations including: - Create/build a BST from a list of numbers - Perform recursive inorder, preorder, and postorder traversals of the BST - Insert new nodes into the BST - Delete nodes from the BST - Copy an existing BST to create a new mirrored/reflected tree - Count the total, leaf, and non-leaf nodes in the BST The program allows the user to select which BST operation to perform and outputs the results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

S.Y.B.Sc.

(Computer Science)
Data Structure and Algorithms -II
Practical Course on CS 241
Program: 1) C program to implement BST to perform following operations on
BST-create, recursive traversal- inorder, preorder, postorder.

#include<stdio.h>
#include<malloc.h>
#define MAX 20
typedef struct node
{
int info;
struct node *left,*right;
} NODE;

/***TREE FUNCTION***/
NODE * createbst(NODE * root)
{
NODE *newnode,*temp;
int i,n,num;
printf("How many nodes:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
newnode=(NODE*)malloc(sizeof(NODE));
printf("Enter the elements:");
scanf("%d",&num);
newnode->info=num;
newnode->left=newnode->right=NULL;
/attach newnode to the tree/
if(root==NULL)
root=newnode;
else
{
temp=root;
while(1)
{
if(num<temp->info)
if(temp->left==NULL) /temp does not have left child/
{
temp->left=newnode; /attach node/
break;
}
else
temp=temp->left; /move temp left/
else
if(temp->right==NULL)
{
temp->right=newnode; /attach newnode/
break;
}
else
temp=temp->right;
}/End while/
}/End else/
}/End for/
return(root);
}
void preorder(NODE * root)
{
NODE *temp=root;
if(temp!=NULL)
{
printf("%d\n",temp->info); //Data
preorder(temp->left); //left
preorder(temp->right); //right
}
}
void inorder(NODE * root)
{
NODE *temp=root;
if(temp!=NULL)
{
inorder(temp->left); //left
printf("%d\n",temp->info);//Data
inorder(temp->right); //right
}
}
void postorder(NODE * root)
{
NODE *temp=root;
if(temp!=NULL)
{
postorder(temp->left); //left
postorder(temp->right); //right
printf("%d\n",temp->info); //data
}
}

int main()
{
int n,choice;
NODE *root=NULL;
do
{
printf("\n1:CREATE");
printf("\n2: RECURSIVE TRAVERSALS");

printf("\n Enter your choice:");


scanf("%d",&choice);
switch(choice)
{
case 1:/CREATE/
root=createbst(root);
break;
case 2:/STRING REVERSALS/
printf("\npreorder traversal is :\n");
preorder(root);
printf("\nInorder traversal is :\n");
inorder (root);
printf("\npostorder traversal is:\n");
postorder(root);
break;

}
} while(choice<=2);
}

/****
Output:

1:CREATE
2: RECURSIVE TRAVERSALS
Enter your choice:1
How many nodes:7
Enter the elements:10
Enter the elements:20
Enter the elements:15
Enter the elements:5
Enter the elements:1
Enter the elements:6
Enter the elements:13
1:CREATE
2: RECURSIVE TRAVERSALS
Enter your choice:2

preorder traversal is :
10 5 1 6 20 15 13

Inorder traversal is :
1 5 6 10 13 15 20

postorder traversal is:


1 6 5 13 15 20 10
****/
Program: 2) C program to implement BST to perform following operations on
BST-insert, delete.

#include<stdio.h>
#include<malloc.h>
#define MAX 3
typedef struct node
{
int info;
struct node *left,*right;
} NODE;
NODE * insertbst(NODE * root)
{
NODE *newnode,*temp, *parent;
int i,n,num;
printf("How many nodes:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
newnode=(NODE*)malloc(sizeof(NODE));
printf("Enter the elements:");
scanf("%d",&num);
newnode->info=num;
newnode->left=newnode->right=NULL;
/attach newnode to the tree/
if(root==NULL)
{
root = newnode;
continue;
}
temp=root;
while(temp!=NULL)
{
parent=temp;
if(num < temp->info)
temp=temp->left;
else
temp=temp->right;
}
if(num < parent->info)
parent->left=newnode;
else
parent->right=newnode;
}//end for
return(root);
}

void print2Duntil(NODE * root, int space)


{
int i;
if(root==NULL)
return;
space += MAX;
print2Duntil(root->right, space);

printf("\n");
for(i= MAX; i< space; i++)
printf("--");
printf("%d", root->info);

print2Duntil(root->left, space);

void print2D(NODE * root)


{
print2Duntil(root, 0);
}
NODE * deletebst(NODE * root, int key)
{
NODE * temp;
if(root==NULL)return root;
if(key< root->info)
root->left=deletebst(root->left, key);
else if(key>root->info)
root->right=deletebst(root->right, key);
else
{
if(root->left==NULL)
{
temp=root->right;
free(root);
return temp;
}
else if(root->right==NULL)
{
temp=root->left;
free(root);
return temp;
}
temp=root->right;
while(temp && temp->left !=NULL)
temp=temp->left;
root->info=temp->info;
root->right=deletebst(root->right, temp->info);
}
return root;
}
int main()
{
int n,choice,key,count;
NODE *root=NULL ;
do
{
printf("\n1:INSERT");
printf("\n2:Delete");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:/CREATE/
root=insertbst(root);
print2D(root);
break;
case 2:
printf("Enter the element to be deleted:");
scanf("%d", &key);
root=deletebst(root, key);
print2D(root);
break;

}
} while(choice!=2);
}

/*
Output:-

1:INSERT
2:Delete
Enter your choice:1
How many nodes:13
Enter the elements:8
Enter the elements:3
Enter the elements:11
Enter the elements:1
Enter the elements:5
Enter the elements:9
Enter the elements:14
Enter the elements:6
Enter the elements:10
Enter the elements:12
Enter the elements:15
Enter the elements:7
Enter the elements:13
------------15
------------14
------------13
------------12
------------11
------------10
------------9
------------8
------------7
------------6
-----------5
----------3
----------1
1:INSERT
2:Delete
Enter your choice:2
Enter the element to be deleted:11

------------15
------------14
------------13
------------12
------------11
------------10
------------9
------------8
------------7
------------6
-----------5
----------3
----------1
**/
Program: 3) C program to implement BST to perform following operations on
BST-copy, mirror image of BST,counting leaf,nonleaf and total nodes.

#include<stdio.h>
#include<malloc.h>
#define MAX 3
typedef struct node
{
int info;
struct node *left,*right;
} NODE;
NODE * createbst(NODE * root)
{
NODE *newnode,*temp, *parent;
int i,n,num;
printf("How many nodes:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
newnode=(NODE*)malloc(sizeof(NODE));
printf("Enter the elements:");
scanf("%d",&num);
newnode->info=num;
newnode->left=newnode->right=NULL;
/attach newnode to the tree/
if(root==NULL)
{
root = newnode;
continue;
}
temp=root;
while(temp!=NULL)
{
parent=temp;
if(num < temp->info)
temp=temp->left;
else
temp=temp->right;
}
if(num < parent->info)
parent->left=newnode;
else
parent->right=newnode;
}//end for
return(root);
}
NODE * treecopy(NODE * root)
{
NODE * newnode;
if(root!=NULL)
{
newnode=(NODE *)malloc(sizeof(NODE));
newnode->info=root->info;
newnode->left=treecopy(root->left);
newnode->right=treecopy(root->right);
return(newnode);
}
else
return NULL;
}
NODE * mirror(NODE * root)
{
NODE * temp = root, *temp1;
if(temp!=NULL)
{
if(temp->left!=NULL)
mirror(temp->left);
if(temp->right!=NULL)
mirror(temp->right);
temp1 = temp->left;
temp->left = temp->right;
temp->right = temp1;
}
}
int Cnodes(NODE * root)
{
static int count = 0;
NODE * temp = root;
if(temp!=NULL)
{
count++;
Cnodes(temp->left);
Cnodes(temp->right);
}
return count;
}
int Cleaf(NODE * root)
{
static int leaf = 0;
NODE * temp = root;
if(temp!=NULL)
{
if((temp->left==NULL) && (temp->right==NULL))
leaf++;
Cleaf(temp->left);
Cleaf(temp->right);
}
return leaf;
}
int Cnonleaf(NODE * root)
{
static int count = 0;
NODE * temp = root;
if(temp!=NULL)
{
if((temp->left!=NULL) && (temp->right!=NULL))
count++;
Cnonleaf(temp->left);
Cnonleaf(temp->right);
}
return count;
}
void inorder(NODE * root)
{
NODE *temp=root;
if(temp!=NULL)
{
inorder(temp->left); //left
printf("%d\t",temp->info);//Data
inorder(temp->right); //right

}
}
int main()
{
int n,choice,key,count;
NODE *root=NULL, *root1=NULL, *root2=NULL;
do
{
printf("\n\n1:CREATE");
printf("\n2:Treecopy");
printf("\n3:Mirror");
printf("\n4:Count Total Nodes");
printf("\n5:Count Leaf Nodes");
printf("\n6:Count nonLeaf Nodes");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:/CREATE/
root=createbst(root);
inorder(root);
break;
case 2:
printf("\nOriginal tree is:\n");
inorder(root);
printf("\nCopy of the tree is:\n");
root1=treecopy(root);
inorder(root1);
break;

case 3:

printf("\nOriginal tree is:\n");


inorder(root);
printf("\nThe mirror of given tree is:\n");
root2 = mirror(root);
inorder(root2);
break;
case 4:

printf("Total Nodes in Tree = %d",Cnodes(root));


break;
case 5:
printf("Total leaf nodes in Tree = %d",Cleaf(root));
break;
case 6:
printf("Total nonleaf nodes in Tree = %d",Cnonleaf(root));
break;

}
} while(choice!=6);
}

/*
Output
1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:1
How many nodes:6
Enter the elements:10
Enter the elements:6
Enter the elements:20
Enter the elements:2
Enter the elements:9
Enter the elements:30
2 6 9 10 20 30

1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:2

Original tree is:


2 6 9 10 20 30
Copy of the tree is:
2 6 9 10 20 30

1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:3

Original tree is:


2 6 9 10 20 30
The mirror of given tree is:
30 20 10 9 6 2

1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:4
Total Nodes in Tree = 6

1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:5
Total leaf nodes in Tree = 3
1:CREATE
2:Treecopy
3:Mirror
4:Count Total Nodes
5:Count Leaf Nodes
6:Count nonLeaf Nodes
Enter your choice:6
Total nonleaf nodes in Tree = 2
*/
Program: 4) C program to implement BST to perform level order traversal of
BST using queue.

#include<stdio.h>
#include<malloc.h>
#define MAX 20
typedef struct node
{
int info;
struct node *left,*right;
} NODE;

typedef struct
{
NODE * data[MAX];
int front, rear;
}QUEUE;
void initq(QUEUE *pq)
{
pq->front = pq->rear = -1;
}
void addq(QUEUE *pq, NODE * treenode)
{
pq->rear++;
pq->data[pq->rear] = treenode;
}
NODE * removeq(QUEUE *pq)
{
pq->front++;
return pq->data[pq->front];

}
int isempty(QUEUE *pq)
{
return(pq->front == pq->rear);
}
int isfull(QUEUE *pq)
{
return(pq->rear==MAX-1);
}

NODE * createbst(NODE * root)


{
NODE *newnode,*temp;
int i,n,num;
printf("How many nodes:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
newnode=(NODE*)malloc(sizeof(NODE));
printf("Enter the elements:");
scanf("%d",&num);
newnode->info=num;
newnode->left=newnode->right=NULL;
/attach newnode to the tree/
if(root==NULL)
root=newnode;
else
{
temp=root;
while(1)
{
if(num<temp->info)
if(temp->left==NULL) /temp does not have left child/
{
temp->left=newnode; /attach node/
break;
}
else
temp=temp->left; /move temp left/
else
if(temp->right==NULL)
{
temp->right=newnode; /attach newnode/
break;
}
else
temp=temp->right;
}/End while/
}/End else/
}/End for/
return(root);
}
void levelorder(NODE *root)
{
int i, level=0;
NODE *temp, *marker=NULL;
QUEUE q;
initq(&q);
addq(&q,root);
addq(&q,marker);
printf("\n level %d -->",level);
while(!isempty(&q))
{
temp=removeq(&q);
if(temp==marker)
{
level++;
if(!isempty(&q))
{
addq(&q, marker);
printf("\n level %d -->", level);

}
}
else
{
printf("%d\t", temp->info);
if(temp->left)
addq(&q, temp->left);
if(temp->right)
addq(&q, temp->right);
}
}
}
int main()
{
int n,choice;
NODE *root=NULL;
do
{
printf("\n1:CREATE");
printf("\n2: RECURSIVE TRAVERSALS");
printf("\n\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:/CREATE/
root=createbst(root);
break;
case 2:
printf("\nlevelorder traversal is:\n");
levelorder(root);

break;

}
} while(choice<=2);
}

/*
Output:-

1:CREATE
2: RECURSIVE TRAVERSALS

Enter your choice:1


How many nodes:5
Enter the elements:10
Enter the elements:20
Enter the elements:5
Enter the elements:7
Enter the elements:15

1:CREATE
2: RECURSIVE TRAVERSALS
Enter your choice:2
levelorder traversal is:
level 0 -->10
level 1 -->5 20
level 2 -->7 15

*/
Program: 5) C program to implement applications of binary tree for set of
elements using heap sort.
#include<stdio.h>
void display(int arr[],int n)
{
int i;
for(i=0; i<n; i++)
printf("%d\t", arr[i]);
}

void heapify(int a[], int top, int last)


{
int j, temp, key;
key = a[top];
j = 2*top+1;
if( (j<last) && (a[j] < a[j+1]) )
j = j+1;
if( (j<=last) && (key<a[j]) )
{
temp = a[top];
a[top] = a[j];
a[j] = temp;
heapify(a,j,last);

}
}
void buildheap(int a[], int n)
{
int i;
for(i=n/2-1; i>=0; i--)
heapify(a,i,n-1);
}

void heapsort(int a[], int n)


{
int i, temp, top=0, last;
buildheap(a,n);
printf("Initial heap = ");
display(a,n);
for(last=n-1; last>=1; last--)
{
temp = a[top];
a[top] = a[last];
a[last] = temp;
printf("\n\nAfter iteration %d : ", n-last);
display(a,n);
heapify(a,top,last-1);

}
}

int main()
{
int a[8] = {26,5,77,1,61,11,59,15};
heapsort(a,8);
return 0;
}

/*
Output
Initial heap = 77 61 59 15 5 11 26 1

After iteration 1 : 1 61 59 15 5 11 26 77

After iteration 2 : 26 15 59 1 5 11 61 77

After iteration 3 : 11 15 26 1 5 59 61 77

After iteration 4 : 5 15 11 1 26 59 61 77

After iteration 5 : 1 5 11 15 26 59 61 77

After iteration 6 : 1 5 11 15 26 59 61 77

After iteration 7 : 1 5 11 15 26 59 61 77
*/
Program: 6) C program to implement applications of binary tree for encode a
set of characters using haffman encoding.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 20
//Binary Tree node
typedef struct node
{
char code[10];
char ch;
int freq;
struct node *left, *right;
} node;
//Priority queue
typedef struct
{
node * data[MAXSIZE];
int front,rear;
} QUEUE;
void initq(QUEUE *pq)
{
pq->front=pq->rear=-1;
}
void addq(QUEUE *pq, node * num)
{
int i;
for(i=pq->rear; i > pq->front; i--) //loop for comparison..
if(num->freq < pq->data[i]->freq)
pq->data[i+1]=pq->data[i]; //shift element...
else
break;
pq->data[i+1]=num;
pq->rear++;
}
node * removeq(QUEUE *pq)
{
node * num;
pq->front++;
num=pq->data[pq->front];
return(num);
}
int isempty(QUEUE *pq)
{
return(pq->front == pq->rear);
}
node *getnode(char ch, int f)
{
node * ptr;
ptr=(node*)malloc(sizeof(node));
ptr->ch=ch;
ptr->freq=f;
strcpy(ptr->code,"code=");
ptr->left=ptr->right=NULL;
return ptr;
}
void encode(node *root)
{
//assign 0 to left branch,1 to right branch
if(root!=NULL)
{
if((root->left==NULL)&&(root->right==NULL))
printf("\n%c->%d->%s", root->ch, root->freq, root->code);
if(root->left!=NULL)
{
strcpy(root->left->code, root->code); /copy print of the code/
strcat(root->left->code,"0"); /append 0/
encode(root->left); /recursive call for left subtree/
}
if(root->right!=NULL)
{
strcpy(root->right->code, root->code); /copy print of the code/
strcat(root->right->code, "1"); /append 1/
encode(root->right); /recursive call for right subtree/
}
}
}
void huffman(node *list[], int n)
{
int i, sum;
node *t1, *t2, *t3;
QUEUE q;
initq(&q);
/Add all no nodes to priority queue/
for(i=0; i<n; i++)
addq(&q, list[i]);
/Construct tree/
while(1)
{
t1=removeq(&q);
if(isempty(&q))/If there is only one node,only one tree is left/
break;
t2=removeq(&q);
t3=getnode('-',t1->freq+t2->freq); /Create subtree root/
t3->left=t1; /Add left child/
t3->right=t2; /Add right child/
addq(&q,t3); /add tree to priority queue/
}
encode(t1);
}
int main()
{
int n, i, f;
char ch;
node * newnode;
node * list[10];
printf("How many characters:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter the character & frequencies:\n");
scanf("%s", &ch);
scanf("%d", &f);
list[i]=getnode(ch, f);
}
huffman(list, n);
return 0;
}

/*
Output:
How many characters:5
Enter the character & frequencies:a 5
Enter the character & frequencies:c 10
Enter the character & frequencies:f 20
Enter the character & frequencies:d 10
Enter the character & frequencies:e 15

d->10->code=00
e->15->code=01
a->5->code=100
c->10->code=101
f->20->code=11

*/
Program: 7) C program to implement graph as adjacency matrix and
adjacency list.

#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int vertex;
struct node *next;
}NODE;
NODE *list[10];

void createmat(int m[10][10], int n)


{
int i,j;
char ans;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
m[i][i]=0;
if(i!=j)
{
printf("Is there an edge between %d and %d (1/0) :
",i+1,j+1);
scanf("%d", &m[i][j]);
}
}
}

void dispmat(int m[10][10], int n)


{
int i,j;
printf("\nThe adjacency matrix is :\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%5d", m[i][j]);
printf("\n");
}
}

void createlist(int m[10][10], int n)


{
int i,j;
struct node *temp, *newnode;
for(i=0; i<n; i++)
{
list[i]=NULL;
for(j=0; j<n; j++)
{
if(m[i][j]==1)
{
newnode=(NODE *)malloc(sizeof(NODE));
newnode->next=NULL;
newnode->vertex=j+1;
if(list [i]==NULL)
list[i]=temp=newnode;
else
{
temp->next=newnode;
temp=newnode;
}
}
}
}
}

void displist(int n)
{
struct node *temp;
int i;
printf("\nThe adjacency list is:\n");
for(i=0; i<n; i++)
{
printf("\nv%d :", i+1);
temp=list[i];
while(temp)
{
printf("v%d ->", temp->vertex);
temp=temp->next;
}
printf("NULL");
}
}

void main()
{
int m[10][10], n;
printf("\nEnter the number of vertices:");
scanf("%d", &n);
createmat(m,n);
dispmat(m,n);
createlist(m,n);
displist(n);
}

/*
Output:-
Enter the number of vertices:4
Is there an edge between 1 and 2 (1/0) : 1
Is there an edge between 1 and 3 (1/0) : 1
Is there an edge between 1 and 4 (1/0) : 0
Is there an edge between 2 and 1 (1/0) : 0
Is there an edge between 2 and 3 (1/0) : 0
Is there an edge between 2 and 4 (1/0) : 1
Is there an edge between 3 and 1 (1/0) : 0
Is there an edge between 3 and 2 (1/0) : 1
Is there an edge between 3 and 4 (1/0) : 1
Is there an edge between 4 and 1 (1/0) : 0
Is there an edge between 4 and 2 (1/0) : 0
Is there an edge between 4 and 3 (1/0) : 0

The adjacency matrix is :


0 1 1 0
0 0 0 1
0 1 0 1
0 0 0 0

The adjacency list is:

v1 :v2 ->v3 ->NULL


v2 :v4 ->NULL
v3 :v2 ->v4 ->NULL

*/
Program: 8) C program to calculate indegree and outdegree and total degree
of all vertices in a graph . The graph is accepted as adjacency matrix

#include <stdio.h>
void main()
{
int m[10][10],r,c,sumin,sumout,n,v,i;
printf("how many vertices:");
scanf("%d",&n);
for(r=0;r<n;r++)
for(c=0;c<n;c++)
{
m[r][c]=0;
if(r!=c)
{
printf("is there an edge between %d and %d(1/0):",r+1,c+1);
scanf("%d",&m[r][c]);
}
}
printf("\n\nVertex Indegree Outdegree Total degree\n");
for(v=0;v<n;v++)
{
sumin=sumout=0;
for(i=0;i<n;i++)
{
sumin=sumin+m[i][v];
sumout=sumout+m[v][i];
}
printf("%d\t\t%d\t\t%d\t\t%d\n",v+1,sumin,sumout,sumin+sumout);
}
}

/*
Output :
how many vertices:3
is there an edge between 1 and 2(1/0):1
is there an edge between 1 and 3(1/0):1
is there an edge between 2 and 1(1/0):0
is there an edge between 2 and 3(1/0):1
is there an edge between 3 and 1(1/0):0
is there an edge between 3 and 2(1/0):0

Vertex Indegree Outdegree Total degree


1 0 2 2
2 1 1 2
3 2 0 2

*/
Program: 9) C program to implement graph traversal method using depth
first search.

#include<stdio.h>
#define MAX 10
typedef struct
{
int data[MAX];
int top;
}STACK;
void initstack(STACK * ps)
{
ps->top=-1;
}
void push(STACK *ps, int num)
{
ps->data[++ps->top]=num;
}
int pop(STACK *ps)
{
return(ps->data[ps->top--]);
}
int isempty(STACK *ps)
{
return(ps->top==-1);
}
int isfull(STACK *ps)
{
return (ps->top==MAX-1);
}

void dfs(int m[10][10], int n)


{
int i, v, w, found;
int visited[10]={0};
STACK s;
initstack(&s);
v=0;
visited[v]=1;
push(&s,v);
printf("v%d" ,v+1);
while(1)
{
found=0;
for(w=0; w<n; w++)
{
if((m[v][w]==1)&&(visited[w]==0))
{
push(&s, w);
printf("v%d", w+1);
visited[w]=1;
v = w;
found = 1;
break;
}
}
if(found == 0)// did not find an adjacent unvisited vertex
if(isempty(&s))
break;
else
v = pop(&s);
}
}
int recdfs(int m[10][10], int n, int v)
{
int w;
static int visited[10]={0};
visited[v]=1;
printf("v%d" ,v+1);
for(w=0; w<n; w++)
{
if( (m[v] [w]==1) && (visited[w]==0) )
recdfs(m,n,w);
}
}

int main()
{
int m[10][10], n, i, j, w;
printf("\nHow many vertices:");
scanf("%d", &n);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(i!=j)
{
printf("Is there edge between vertex %d and %d
(1/0):", i+1, j+1);
scanf("%d", &m[i][j]);
}
}
printf("\nNon recursive depth first search is :");
dfs(m,n);
printf("\nRecursive depth first search is :");
recdfs(m,n,0);
}

/*
Output:-
How many vertices:5
Is there edge between vertex 1 and 2 (1/0):0
Is there edge between vertex 1 and 3 (1/0):1
Is there edge between vertex 1 and 4 (1/0):1
Is there edge between vertex 1 and 5 (1/0):0
Is there edge between vertex 2 and 1 (1/0):0
Is there edge between vertex 2 and 3 (1/0):1
Is there edge between vertex 2 and 4 (1/0):0
Is there edge between vertex 2 and 5 (1/0):1
Is there edge between vertex 3 and 1 (1/0):0
Is there edge between vertex 3 and 2 (1/0):1
Is there edge between vertex 3 and 4 (1/0):0
Is there edge between vertex 3 and 5 (1/0):0
Is there edge between vertex 4 and 1 (1/0):0
Is there edge between vertex 4 and 2 (1/0):0
Is there edge between vertex 4 and 3 (1/0):0
Is there edge between vertex 4 and 5 (1/0):1
Is there edge between vertex 5 and 1 (1/0):0
Is there edge between vertex 5 and 2 (1/0):0
Is there edge between vertex 5 and 3 (1/0):0
Is there edge between vertex 5 and 4 (1/0):0

Non recursive depth first search is :v1v3v2v5v4


recursive depth first search is :v1v3v2v5v4

*/
Program: 10) C program to implement graph traversal method using breadth
first search.

#include<stdio.h>
#define MAX 10
typedef struct
{
int data[MAX];
int front, rear;
}QUEUE;
/**functions****/
void initq(QUEUE *pq)
{
pq->front = pq->rear = -1;
}
void addq(QUEUE *pq, int num)
{
pq->rear++;
pq->data[pq->rear] = num;
}
int removeq(QUEUE *pq)
{
int num;
pq->front++;
num=pq->data[pq->front];
return(num);
}
int isempty(QUEUE *pq)
{
return(pq->front == pq->rear);
}
int isfull(QUEUE *pq)
{
return(pq->rear==MAX-1);
}
void bfs(int m[10][10], int n)
{
int i, v, w;
int visited[10]={0};
QUEUE q;
initq(&q);

v=0;
visited[v]=1;
addq(&q,v);
while(!isempty(&q))
{

v=removeq(&q);
printf("v%d",v+1);
for(w=0; w<n; w++)
{
if((m[v][w]==1)&&(visited[w]==0))
{
addq(&q, w);

visited[w]=1;

}
}

}
}

int main()
{
int m[10][10], n, i, j, w;
printf("\nHow many vertices:");
scanf("%d", &n);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(i!=j)
{
printf("Is there edge between vertex %d and %d
(1/0):", i+1, j+1);
scanf("%d", &m[i][j]);
}
}
printf("\nNon recursive breadth first search is :");
bfs(m,n);

}
/*
Output:-
How many vertices:5
Is there edge between vertex 1 and 2 (1/0):0
Is there edge between vertex 1 and 3 (1/0):1
Is there edge between vertex 1 and 4 (1/0):1
Is there edge between vertex 1 and 5 (1/0):0
Is there edge between vertex 2 and 1 (1/0):0
Is there edge between vertex 2 and 3 (1/0):0
Is there edge between vertex 2 and 4 (1/0):0
Is there edge between vertex 2 and 5 (1/0):1
Is there edge between vertex 3 and 1 (1/0):0
Is there edge between vertex 3 and 2 (1/0):1
Is there edge between vertex 3 and 4 (1/0):0
Is there edge between vertex 3 and 5 (1/0):0
Is there edge between vertex 4 and 1 (1/0):0
Is there edge between vertex 4 and 2 (1/0):0
Is there edge between vertex 4 and 3 (1/0):0
Is there edge between vertex 4 and 5 (1/0):1
Is there edge between vertex 5 and 1 (1/0):0
Is there edge between vertex 5 and 2 (1/0):0
Is there edge between vertex 5 and 3 (1/0):0
Is there edge between vertex 5 and 4 (1/0):0
Non recursive breadth first search is :v1v3v4v2v5
*/
Program: 11) Program for implementation of topological sorting.

#include<stdio.h>
#define MAX 20

typedef struct
{
int data[MAX];
int top;
}STACK;

void init(STACK * ps)


{
ps->top=-1;
}
void push(STACK *ps, int num)
{
ps->data[++ps->top]=num;
}
int pop(STACK *ps)
{
return(ps->data[ps->top--]);
}
int isempty(STACK *ps)
{
return(ps->top==-1);
}
int isfull(STACK *ps)
{
return (ps->top==MAX-1);
}

int topoSort(int m[4][4], int n)


{
int i,v,j,w;
int visited[10]={0};
int indeg[10]={0};
/calculate the indegree/
for(i=0; i<n; i++)
for(j=0; j<n; j++)
indeg[i] = indeg[i] + m[j][i];
STACK s;
init(&s);
while(1)
{
for(v=0; v<n; v++)
if( (visited[v]==0) && (indeg[v]==0) )
{
visited[v]=1;
push(&s, v);
printf("v%d\n", v+1);
}
if(isempty(&s))
break;
v = pop(&s);
for(w=0; w<n; w++)
if(m[v][w]==1)
indeg[w] = indeg[w]-1;//reduce indegrees of adjacent vertices
}
}
int main()
{

int m[4][4] ={ {0,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0} };


topoSort(m,4);

/*
Output
v1
v2
v3
v4
*/
Program:12) C program to accept graph as set of edges sorts the edges and
applies kruskals Algorithm.

#include <stdio.h>
int i,j,k,a,b,u,v,n,e=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}

int uni(int i,int j)


{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

void main()
{
printf("Enter the no. of vertices:");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\n");
while(e<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",e++,a,b,min);
mincost+=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost = %d\n",mincost);
}

/*
Output
Enter the no. of vertices:3
Enter the adjacency matrix:
0
5
3
5
0
4
3
4
0

1 edge (1,3) =3
2 edge (2,3) =4

Minimum cost = 7
*/
Program 13:C program for greedy strategy for finding the minimum spannig
tree of a graph using primes algorithm.

#include<stdio.h>
int a,b,u,v,n,i,j,e=1;
int visited[10]= {0},min,mincost=0,cost[10][10];
void main()
{

printf("Enter the number of vertices:");


scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(e<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",e++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);

/*
Output:-
Enter the number of vertices:3
Enter the adjacency matrix:
0
4
6
4
0
5
6
5
0

Edge 1:(1 2) cost:4


Edge 2:(2 3) cost:5
Minimun cost=9
*/
Program: 14) C program to implementation of Dijkstras shortest path
Algorithm for finding shortest path from a given source vertex using
adjacency cost matrix.

#include<stdio.h>
#define MAX 20

void djks(int c[10][10], int n)


{
int i, j, v, w, u, count, min;
int dist[10];
int visited[10]={0};

printf("\nEnter the source vertex:");


scanf("%d", &v);
v=v-1;
for(i=0; i<n; i++)
dist[i] = c[v][i];
visited[v] = 1;
count = 1;
while(count < n)
{

min = 999;
for(i=0; i<n; i++)
if( (visited[i]==0) && (dist[i] < min))
{
min = dist[i];
u = i;
}

visited[u] = 1;
for(w=0; w<n; w++)
{
if(!visited[w])
if(dist[u] + c[u][w] < dist[w])
dist[w] = dist[u] + c[u][w];
count++;
}
}
printf("\nThe sortest path are:\n");
for(i=0;i<n;i++)
printf("from v%d to v%d = %d\n",v+1,i+1,dist[i]);
}

int main()
{
int c[10][10]={0},n,i,j;
printf("\nHow many vertices:");
scanf("%d",&n);
printf("\nEnter the Adjacency cost matrix:\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(i<j)
{
printf("\nEnter the cost of edge %d->%d :", i+1, j+1);

scanf("%d", &c[i][j]);
c[j][i]= c[i][j];

}
}
djks(c,n);
}

/*
Output:-
How many vertices:3

Enter the Adjacency cost matrix:

Enter the cost of edge 1->2 :15

Enter the cost of edge 1->3 :40

Enter the cost of edge 2->3 :10

Enter the source vertex:1


The sortest path are:
from v1 to v1 = 0
from v1 to v2 = 15
from v1 to v3 = 25

*/
Program: 15) C program to implementation of Floyd Warshalls Algorithm for
all pairs shortest path.

#include <stdio.h>
#define n 4
void printMatrix(int matrix[][n]);
void floydWarshall(int graph[][n])
{
int matrix[n][n], i, j, k;

for (i = 0; i < n; i++)


for (j = 0; j < n; j++)
matrix[i][j] = graph[i][j];

for (k = 0; k < n; k++)


{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
printMatrix(matrix);
}
void printMatrix(int matrix[][n])
{
int i,j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (matrix[i][j] == 999)
printf("%4s", "INF");
else
printf("%4d", matrix[i][j]);
}
printf("\n");
}
}

int main()
{
int graph[n][n] =
{
{0, 8, 999, 1},
{999, 0, 1, 999},
{4, 999, 0, 999},
{999, 2, 9, 0}
};
floydWarshall(graph);
}
/*
Output
0 3 4 1
5 0 1 6
4 7 0 5
7 2 3 0
*/
Program:16) C program of static hash table with linear probing.

#include<stdio.h>
int hf(int key, int i)
{
return (key%10 + i)%10;
}

void insert(int ht[10], int key)


{
int i, index;
for(i=0; i<10; i++)
{
index = hf(key,i);
if(ht[index] == -1)
{
ht[index] = key;
return;
}
}
printf("\ncould not insert key %d\n",key);
}

int search(int ht[10], int key)


{
int i, index;
for(i=0; i<10; i++)
{
index = hf(key,i);
if(ht[index] == key)
return index;
}
return -1;
}
void delkey(int ht[10], int key)
{
int index;
index = search(ht,key);
if(index == -1)
printf("\nkey %d not found\n",key);
else
ht[index] = -1;
}

void showtable(int ht[10])


{
int i;
for(i=0; i<10; i++)
printf("%d[%d]\n", i, ht[i]);
}

int main()
{
int ht[10], choice,i, key, index;
for(i=0; i<10; i++)
ht[i] = -1;
do
{
printf("\n1:Insert\n2:Search\n3:Delete\n4:exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the key to be inserted :");
scanf("%d",&key);
insert(ht,key);
showtable(ht);
break;
case 2:
printf("\nEnter the key to be serched : ");
scanf("%d",&key);
index = search(ht,key);
if(index == -1)
printf("\nkey %d not found",key);
else
printf("\n%d found at position %d",key,index);
break;
case 3:
printf("\nEnter the key to be deleted :");
scanf("%d",&key);
delkey(ht,key);
showtable(ht);
}
}while(choice!=4);
return 0;
}

/*
Output:-
1:Insert
2:Search
3:Delete
4:exit
Enter your choice:1

Enter the key to be inserted :42


0[-1]
1[-1]
2[42]
3[-1]
4[-1]
5[-1]
6[-1]
7[-1]
8[-1]
9[-1]

1:Insert
2:Search
3:Delete
4:exit
Enter your choice:1

Enter the key to be inserted :23


0[-1]
1[-1]
2[42]
3[23]
4[-1]
5[-1]
6[-1]
7[-1]
8[-1]
9[-1]

1:Insert
2:Search
3:Delete
4:exit
Enter your choice:1

Enter the key to be inserted :12


0[-1]
1[-1]
2[42]
3[23]
4[12]
5[-1]
6[-1]
7[-1]
8[-1]
9[-1]

1:Insert
2:Search
3:Delete
4:exit
Enter your choice:3

Enter the key to be deleted :23


0[-1]
1[-1]
2[42]
3[-1]
4[12]
5[-1]
6[-1]
7[-1]
8[-1]
9[-1]

*/
Program:17) C program for implementation of static hash table with
chaining.

#include<stdio.h>
typedef struct
{
int key;
int chain;
}HT;
void initialize(HT ht[10])
{
int i;
for( i=0;i<10;i++)
ht[i].key=ht[i].chain=-1;
}
int hf(int key,int i)
{
return (key%10 + i)%10;
}
void ShowTable(HT ht[10])
{
int i;
for(i=0;i<10;i++)
printf("%d[%d][%d]\n",i,ht[i].key,ht[i].chain);
}
void insert(HT ht[10],int key)
{
int index,oldindex,i=0;

index=hf(key,i);
if(ht[index].key == -1)//empty bucket
ht[index].key = key;
else
{
/* reach the end of the chain*/
while(ht[index].chain!=-1)
index=ht[index].chain;
oldindex=index;
for(i=1;i<10;i++)//find new location
{
index=hf(key,i);
if(ht[index].key==-1)//empty bucket
{
ht[index].key=key;
ht[oldindex].chain=index;//form the chain
return;
}
}
}
}
int search(HT ht[10],int key)
{
int index,i;
index = hf(key,i);
while(index!=-1)
{
if(ht[index].key==key)
return index;
else
index=ht[index].chain;
}
return -1;
}
int main ()
{ HT ht[10];
int choice,key;
initialize(ht);
do
{
printf("\n1:Insert\n2:exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the key to be inserted :");
scanf("%d",&key);
insert(ht,key);
ShowTable(ht);
break;
}
}while(choice!=2);
return 0;
}
/*
Output:-
1:Insert
2:exit
Enter your choice:1

Enter the key to be inserted :11


0[-1][-1]
1[11][-1]
2[-1][-1]
3[-1][-1]
4[-1][-1]
5[-1][-1]
6[-1][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :32


0[-1][-1]
1[11][-1]
2[32][-1]
3[-1][-1]
4[-1][-1]
5[-1][-1]
6[-1][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :41


0[-1][-1]
1[11][3]
2[32][-1]
3[41][-1]
4[-1][-1]
5[-1][-1]
6[-1][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :54


0[-1][-1]
1[11][3]
2[32][-1]
3[41][-1]
4[54][-1]
5[-1][-1]
6[-1][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :33


0[-1][-1]
1[11][3]
2[32][-1]
3[41][5]
4[54][-1]
5[33][-1]
6[-1][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :61


0[-1][-1]
1[11][3]
2[32][-1]
3[41][5]
4[54][-1]
5[33][6]
6[61][-1]
7[-1][-1]
8[-1][-1]
9[-1][-1]

Enter the key to be inserted :72


0[-1][-1]
1[11][3]
2[32][7]
3[41][5]
4[54][-1]
5[33][6]
6[61][-1]
7[72][-1]
8[-1][-1]
9[-1][-1]

*/
Program: 18) C program for implementation of linked hash table.

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
int key;
struct node *next;
}NODE;
NODE *HT[10]={NULL};
int hf(int key)
{
return(key%10);
}
void insert(int k)
{
int index;
NODE * newnode = NULL, *temp;
newnode = (NODE *)malloc(sizeof(NODE));
newnode->key=k;
newnode->next=NULL;
index=hf(k);
if(HT[index]==NULL)
HT[index]=newnode;
else
{
temp=HT[index];
while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
}
void search(int key)
{
int index;
NODE * temp;
index=hf(key);
for(temp=HT[index]; temp!=NULL; temp=temp->next)
if(temp->key==key)
{
printf("%d found"\n,key);
return;
}
printf("%d not found"\n, key);
}
void deletekey(int key)
{
int index;
NODE *temp;
index=hf(key);
temp=HT[index];
if( (temp!=NULL) && (temp->key==key))
HT[index]=temp->next;
else
{
for(temp=HT[index]; temp!=NULL; temp=temp->next)
if(temp->next->key==key)
{
temp->next=temp->next->next;
return;
}
printf("%d not found\n",key);
}
}
void showtable()
{
int i,index;
NODE *temp;
for(i=0;i<10;i++)
{
printf("| %d | ",i);
for(temp=HT[i]; temp!=NULL; temp=temp->next)
printf("%d -> ",temp->key);
printf("NULL\n");
}
}
int main()
{

int choice,i, key;


for(i=0;i<10;i++)
do
{
printf("\n1:Insert\n2:Delete");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the key to be inserted :");
scanf("%d",&key);
insert(key);
showtable();
break;

case 2:
printf("\nEnter the key to be deleted :");
scanf("%d",&key);
deletekey(key);
showtable();
}
}while(choice!=2);
return 0;
}

/*
Output:-
1:Insert
2:Delete
Enter your choice:1

Enter the key to be inserted :80


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | NULL
| 4 | NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | NULL
| 9 | NULL

Enter the key to be inserted :23


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> NULL
| 4 | NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | NULL
| 9 | NULL

Enter the key to be inserted :34


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | NULL
| 9 | NULL

Enter the key to be inserted :48


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> NULL
| 9 | NULL

Enter the key to be inserted :73


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> 73 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> NULL
| 9 | NULL

Enter the key to be inserted :93


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> 73 -> 93 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> NULL
| 9 | NULL

Enter the key to be inserted :78


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> 73 -> 93 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> 78 -> NULL
| 9 | NULL

Enter the key to be inserted :55


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> 73 -> 93 -> NULL
| 4 | 34 -> NULL
| 5 | 55 -> NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> 78 -> NULL
| 9 | NULL
1:Insert
2:Delete
3:exit
Enter your choice:2

Enter the key to be deleted :55


| 0 | 80 -> NULL
| 1 | NULL
| 2 | NULL
| 3 | 23 -> 73 -> 93 -> NULL
| 4 | 34 -> NULL
| 5 | NULL
| 6 | NULL
| 7 | NULL
| 8 | 48 -> 78 -> NULL
| 9 | NULL

*/

You might also like