Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Stuctures

You are on page 1of 159

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

II/IV B.Tech I Semester


A.Y.2018-19
LAB MANUAL
COURSE NAME : DATA STRUCTURES
COURSE CODE : 17CS1102
L-T-P STRUCTURE : 3-0-2
COURSE CREDITS :4
COURSE CORDINATOR : Dr. G PRADEEPINI

COURSE INSTRUCTORS:

1. Dr P Sai Kiran 7. Mr S. Dora Babu


2. Dr Amarendra 8. MD.AR.Quadri
3. Mr. M Vishnuvardhan 9. Mr V Kantha Rao
4. Mr. P.Venkateswara Rao 10. Mr. Jetti Kumar
5. Mr. Bhupesh Deka 11. Mr. T. Jagadeesh
6. Mr. Ch Sai Baba 12. Mrs. Aruna Sri
13. Mr. P. Vikram

Signature of Course Coordinator Signature of HOD, CSE


Organization of the Laboratory :
The laboratory framework includes a creative element but shifts the time-intensive aspects outside of
the Two-Hour closed laboratory period. Within this structure, each laboratory includes three parts:
Pre-lab, In-lab, and Post-lab.

Pre-lab

The Pre-lab exercise is a homework assignment that links the lecture with the laboratory period -
typically takes 2 hours to complete. The goal is to synthesize the information they learn in lecture
with material from their textbook to produce a working piece of software. Pre-lab Students attending a
two-hour closed laboratory are expected to make a good-faith effort to complete the Pre-lab exercise
before coming to the lab. Their work need not be perfect, but their effort must be real (roughly 80
percent correct).

In-lab

The In-lab section takes place during the actual laboratory period. The First hour of the laboratory
period can be used to resolve any problems the students might have experienced in completing the
Pre-lab exercises. The intent is to give constructive feedback so that students leave the lab with
working Pre-lab software - a significant accomplishment on their part. During the second hour,
students complete the In-lab exercise to reinforce the concepts learned in the Pre-lab. Students leave
the lab having received feedback on their Pre-lab and In-lab work.

Post-lab

The last phase of each laboratory is a homework assignment that is done following the laboratory
period. In the Post-lab, students analyze the efficiency or utility of a given system call. Each Post-lab
exercise should take roughly 30 minutes to complete.
List of Experiments supposed to finish in Open Lab Sessions:-

1. Develop a set of programs to implement


a. Linear Search
b. Binary search ( iterative)
c. Binary search (recursive)
2. Develop a set of programs to find the solution for the maximum subsequence sum
problem with different time complexity solutions.
a. Maximum subsequence sum in cubic time
b. Maximum subsequence sum in Logarithmic time
c. Maximum subsequence sum in linear time
3. Develop a set of programs to implement below sorting techniques
a. Insertion Sort
b. Shell sort
c. Selection Sort
4. Develop a set of programs to implement below sorting techniques(Divide and conquer
method)
a. Quick sort
b. Quick Sort with median of three and cut-off 3.
c. Merge Sort
5. Develop a Program to implement
a. single Linked List with insertion, find, delete, add after, reverse, sort and
display operations
b. doubly linked list
c. Circular Linked List
6. Develop a set of programs to implement
a. Stack using Linked List
b. Stack using two Queues
c. Towers of Hanoi using stack
7. Develop a set of programs to implement
a. Circular Queue (array implementation)
b. Queue using Linked List
c. Queue using two Stacks
8. Develop a set of programs to implement applications of Stack
a. Balanced Brackets
b. Infix to Postfix
c. Postfix Expression Evaluation
9. Develop a program to implement Binary Tree with following Operations
a. BST - Find, findmax, findmin, insert
b. BST- Delete, Inorder, Preorder, Postorder traversal
c. Expression Tree
10. Develop a program to perform following operations on AVL tree
a. Node declaration and Function to compute height of an AVL node
b. Insertion with single rotation, Double rotation routines
c. Delete, in-order Traversal.
11. Develop a set of programs to implement the following
a. Hash Table with chaining
b. Open Addressing Hash Table with Quadratic probing and rehashing.
12. Develop a set of programs to implement Binary Heap with following operations
a. Build Heap
b. Percolate up, Percolate Down, Heap sort
c. delete max, Finding nth largest element
13. Develop a set of programs to implement the following graph algorithms using adjacency
list
a. Breadth First Search
b. Depth First Search
c. Dijkstra’s Algorithm
14. Develop a set of Programs to implement the following Minimal Spanning tree
algorithms using adjacency list
a. Prim’s algorithm
b. Kruskal’s algorithm
15. Develop Polynomial ADT using linked list and use it to perform basic operations on two
given expressions.
1 a) Linear Search

https://www.hackerrank.com/contests/17cs1102/challenges/1-a-linear-search

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

int main()

int n;

scanf("%d",&n);

long int a[n];

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

scanf("%ld",&a[i]);

int ele;

scanf("%d",&ele);

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

if(a[i]==ele)

printf("%d",i);

break;

Output:
5
21364
3
2
1 b) Binary Search-Iterative

https://www.hackerrank.com/contests/17cs1102/challenges/1-b-binary-search-iterative

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

int find(long int ele, long int a, long int b, long int arr[])

long int m;

if(a<=b)

m=(a+b)/2;

if(arr[m]==ele)

return 1;

if(arr[m]<ele)

return find(ele,m+1,b,arr);

else return find(ele, a,m-1,arr);

return 0;

int main()

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

long int n,q,ele;

scanf("%ld%ld",&n,&q);

long int a[n];


scanf("%ld",&a[i]);

for(long int i=0;i<q;i++)

scanf("%ld",&ele);

if(find(ele,0,n-1,a)==1)

printf("YES\n");

else

printf("NO\n");

Input:

10 15 20 25 30

10

15

20

35

50

Output:

YES

YES

YES

NO

NO
1. C) Binary Search-Recursive

https://www.hackerrank.com/contests/17cs1102/challenges/1-c-binary-search-recursion/problem

Answer:

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

if(arr[m]<ele)

return find(ele,m+1,b,arr);

else return find(ele, a,m-1,arr);

return 0;

int main()

long int n,q,ele;

scanf("%ld%ld",&n,&q);

long int a[n];

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

scanf("%ld",&a[i]);

for(long int i=0;i<q;i++)

scanf("%ld",&ele);

if(find(ele,0,n-1,a)==1)

printf("YES\n");

else

printf("NO\n");
}

Input:

10 15 20 25 30

10

15

20

35

50

Output:

YES

YES

YES

NO

NO
2.a) Maximum Subsequence Sum-Cubic time

https://www.hackerrank.com/contests/17cs1102/challenges/2a-maximum-subsequence-sum-in-cubic-
time

int find(long int ele, long int a, long int b, long int arr[])

long int m;

if(a<=b)

m=(a+b)/2;

if(arr[m]==ele)

return 1;

Long int MaxSubsequenceSum( long int A[ ], int N )

int ThisSum, MaxSum, i, j, k;

MaxSum = 0;

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

for( j = i; j < N; j++ )

ThisSum = 0;

for( k = i; k <= j; k++ )

ThisSum += A[ k ];

if( ThisSum > MaxSum )

MaxSum = ThisSum;

return MaxSum;

int main()

{
long int n,i;

scanf("%ld",&n);

long int a[n];

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

scanf("%ld",&a[i]);

printf("%ld",MaxSubsequenceSum(a,n));

Input:

-1 3 2 10 1

Output:

16
2 b) Maximum Subsequence Sum-Logarithmic-time
https://www.hackerrank.com/contests/17cs1102/challenges/2b-maximum-subsequence-sum-in-
logarithmic-time

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

long int

Max3( long int A, long int B, long int C )

return A > B ? A > C ? A : C : B > C ? B : C;

int long MaxSubSum( long int A[ ], int Left, int Right )

int MaxLeftSum, MaxRightSum;

int MaxLeftBorderSum, MaxRightBorderSum;

int LeftBorderSum, RightBorderSum;

int Center, i;

if( Left == Right ) /* Base case */

if( A[ Left ] > 0 )

return A[ Left ];

else

return 0;

Center = ( Left + Right ) / 2;

MaxLeftSum = MaxSubSum( A, Left, Center );

MaxRightSum = MaxSubSum( A, Center + 1, Right );

MaxLeftBorderSum = 0; LeftBorderSum = 0;
for( i = Center; i >= Left; i-- )

LeftBorderSum += A[ i ];

if( LeftBorderSum > MaxLeftBorderSum )

MaxLeftBorderSum = LeftBorderSum;

MaxRightBorderSum = 0; RightBorderSum = 0;

for( i = Center + 1; i <= Right; i++ )

RightBorderSum += A[ i ];

if( RightBorderSum > MaxRightBorderSum )

MaxRightBorderSum = RightBorderSum;

return Max3( MaxLeftSum, MaxRightSum,

MaxLeftBorderSum + MaxRightBorderSum );

long int

MaxSubsequenceSum( long int A[ ], long int N )

return MaxSubSum( A, 0, N - 1 );

int main()

long int n,i;


scanf("%ld",&n);

long int a[n];

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

scanf("%ld",&a[i]);

printf("%ld",MaxSubsequenceSum(a,n));

Input:

10

-9 -98 -98 -100 0 0 -34 32 23 456


Output:

511
2C) Maximum Subsequence sum in Linear time

https://www.hackerrank.com/contests/17cs1102/challenges/2c-maximum-subsequence-sum-in-
linear-time

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

long int MaxSubsequenceSum( long int A[ ], int N )

long int ThisSum, MaxSum, j;

ThisSum = MaxSum = 0;

for( j = 0; j < N; j++ )

ThisSum += A[ j ];

if( ThisSum > MaxSum )

MaxSum = ThisSum;

else if( ThisSum < 0 )

ThisSum = 0;

return MaxSum;

int main()

long int n,i;


scanf("%ld",&n);

long int a[n];

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

scanf("%ld",&a[i]);

printf("%ld",MaxSubsequenceSum(a,n));

Input:

4 -3 5 -2 -1 2 6 -2

Output:

11
3 a) Insertion Sort

https://www.hackerrank.com/contests/17cs1102/challenges/3-a-implement-insertion-sort

int main()

int n,i,j,k,key;

scanf("%d",&n);

int a[n];

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

scanf("%d",&a[i]);

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

key=a[i];

for(j=i-1;j>=0;j--)

if(key<a[j])

a[j+1]=a[j];

else

break;

a[j+1]=key;

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

printf("%d ",a[k]);

printf("\n");
}

Input:

10

-10 9 1 8 2 -9 -3 5 24 -99

Output:

-10 9 1 8 2 -9 -3 5 24 -99
-10 9 1 8 2 -9 -3 5 24 -99
-10 1 9 8 2 -9 -3 5 24 -99
-10 1 8 9 2 -9 -3 5 24 -99
-10 1 2 8 9 -9 -3 5 24 -99
-10 -9 1 2 8 9 -3 5 24 -99
-10 -9 -3 1 2 8 9 5 24 -99
-10 -9 -3 1 2 5 8 9 24 -99
-10 -9 -3 1 2 5 8 9 24 -99
-99 -10 -9 -3 1 2 5 8 9 24
b) Shell Sort

https://www.hackerrank.com/contests/17cs1102/challenges/3b-implement-shell-sort

int shellSort(int arr[], int n)

int p,i,temp,j,k;

for (p = n/2; p > 0; p /= 2)

for (i = p; i < n; i += 1)

temp = arr[i];

for (j = i; j >= p && arr[j - p] > temp; j -= p)

arr[j] = arr[j - p];

arr[j] = temp;

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

printf("%d ",arr[k]);

printf("\n");

return 0;

int main()

int n,i;

scanf("%d",&n);

int arr[n];

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


scanf("%d",&arr[i]);

shellSort(arr, n);

return 0;

Input:

10

10 9 8 7 6 5 4 3 2 1

Output:

5 9 8 7 6 10 4 3 2 1
5 4 8 7 6 10 9 3 2 1
5 4 3 7 6 10 9 8 2 1
5 4 3 2 6 10 9 8 7 1
5 4 3 2 1 10 9 8 7 6
3 4 5 2 1 10 9 8 7 6
3 2 5 4 1 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 8 9 10 7 6
1 2 3 4 5 8 7 10 9 6
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
C) Selection Sort

https://www.hackerrank.com/contests/17cs1102/challenges/3c-implement-selection-sort

int main()

int n,i,j,k,min;

scanf("%d",&n);

int a[n];

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

scanf("%d",&a[i]);

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

min=i;

for(j=i+1;j<n;j++)

if(a[min]>a[j])

min=j;

a[i]=(a[i]+a[min])-(a[min]=a[i]);

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

printf("%d ",a[k]);

printf("\n");

Input:

10 5 8 9 20

Output:

5 8 9 10 20
4 a) Quick Sort

#include<stdio.h>

void quicksort(int [10],int,int);

int main()

int x[20],size,i;

printf("Enter size of the array: ");

scanf("%d",&size);

printf("Enter %d elements: ",size);

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

scanf("%d",&x[i]);

quicksort(x,0,size-1);

printf("Sorted elements: ");

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

printf(" %d",x[i]);

return 0;

void quicksort(int x[10],int first,int last)

int pivot,j,temp,i;

if(first<last)

pivot=first;

i=first;

j=last;

while(i<j)

while(x[i]<=x[pivot]&&i<last)
i++;

while(x[j]>x[pivot])

j--;

if(i<j)

temp=x[i];

x[i]=x[j];

x[j]=temp;

temp=x[pivot];

x[pivot]=x[j];

x[j]=temp;

quicksort(x,first,j-1);

quicksort(x,j+1,last);

Input:

100 23 45 24 37 78 90 1 7 33 11 29

Output:

1 11 23 24 29 33 37 45 71 78 90 100
4 b)Quick Sort with median of three and cut-off 3

#include <stdlib.h>

#include <stdio.h>

#define Cutoff ( 3 )

void

Swap( int *Lhs, int *Rhs )

int Tmp = *Lhs;

*Lhs = *Rhs;

*Rhs = Tmp;

int

Median3( int A[ ], int Left, int Right )

int Center = ( Left + Right ) / 2;

if( A[ Left ] > A[ Center ] )

Swap( &A[ Left ], &A[ Center ] );

if( A[ Left ] > A[ Right ] )

Swap( &A[ Left ], &A[ Right ] );

if( A[ Center ] > A[ Right ] )

Swap( &A[ Center ], &A[ Right ] );

/* Invariant: A[ Left ] <= A[ Center ] <= A[ Right ] */

Swap( &A[ Center ], &A[ Right - 1 ] ); /* Hide pivot */

return A[ Right - 1 ]; /* Return pivot */


}

void

InsertionSort( int A[ ], int N )

int j, P;

int Tmp;

/* 1*/ for( P = 1; P < N; P++ )

/* 2*/ Tmp = A[ P ];

/* 3*/ for( j = P; j > 0 && A[ j - 1 ] > Tmp; j-- )

/* 4*/ A[ j ] = A[ j - 1 ];

/* 5*/ A[ j ] = Tmp;

void

Qsort( int A[ ], int Left, int Right )

int i, j;

int Pivot;

/* 1*/ if( Left + Cutoff <= Right )

/* 2*/ Pivot = Median3( A, Left, Right );

/* 3*/ i = Left; j = Right - 1;

/* 4*/ for( ; ; )

/* 5*/ while( A[ ++i ] < Pivot ){ }

/* 6*/ while( A[ --j ] > Pivot ){ }


/* 7*/ if( i < j )

/* 8*/ Swap( &A[ i ], &A[ j ] );

else

/* 9*/ break;

/*10*/ Swap( &A[ i ], &A[ Right - 1 ] ); /* Restore pivot */

/*11*/ Qsort( A, Left, i - 1 );

/*12*/ Qsort( A, i + 1, Right );

else /* Do an insertion sort on the subarray */

/*13*/ InsertionSort( A + Left, Right - Left + 1 );

/* END */

main( )

int i;

int A[12]={100,23,45,24,37,78,90,1,71,33,11,29};

Qsort( A, 0,11);

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

printf("\t%d",A[i]);

Output:

1 11 23 24 29 33 37 45 71 78 90 100
4 c) Merge Sort

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void

Merge(int A[],int mpArray[],int Lpos,int Rpos,int RightEnd)

int i,leftEnd,NumElements,TmpPos;

LeftEnd=Rpos-1;

TmpPos=Lpos;

NumElements=RightEnd-Lpos+1;

while(Lpos<=LeftEnd && Rpos<=RightEnd)

if(A[Lpos]<=A[Rpos])

TmpArray[TmpPos++]=A[Lpos++];

else

TmpArray [TmpPos++]=A[Rpos++];

while(Lpos<=LeftEnd)

TmpArray[TmpPos++]=A[Lpos++];

while(Rpos<=RightEnd)

TmpArray[TmpPos++]=A[Rpos++];

for(i=0;i<NumElements;i++,RightEnd--)

A[RightEnd]=TmpArray[RightEnd];

Void Msort(int A[],int TmpArray[],int Left,int Right)

int center;

if(Left<Right)
{

center=(Left+Right)/2;

Msort(A,TmpArray,Left,center);

Msort(A,TmpArray,center+1,Right)

Merge(A,TmpArray,Left,center+1,Right);

main()

int i,TmpArray[12];

int A[12]={100,23,45,24,37,78,90,1,71,33,11,29};

Msort(A,TmpArray,0,11);

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

printf(“\t %d”,A[i]);

Output:

1 11 23 24 29 33 37 45 71 78 90 100
5 a) Single Linked List with insertion, find, delete, add after, reverse, sort and display
operations Source Code

#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;

}*head;

void append(int num)

struct node *temp,*right;

temp= (struct node *)malloc(sizeof(struct node));

temp->data=num;

right=(struct node *)head;

while(right->next != NULL)

right=right->next;

right->next =temp;

right=temp;

right->next=NULL;

void add( int num )

struct node *temp;

temp=(struct node *)malloc(sizeof(struct node));

temp->data=num;

if (head== NULL)

{
head=temp;

head->next=NULL;

else

temp->next=head;

head=temp;

void addafter(int num, int loc)

int i;

struct node *temp,*left,*right;

right=head;

for(i=1;i<loc;i++)

left=right;

right=right->next;

temp=(struct node *)malloc(sizeof(struct node));

temp->data=num;

left->next=temp;

left=temp;

left->next=right;

return;

void insert(int num)

{
int c=0;

struct node *temp;

temp=head;

if(temp==NULL)

add(num);

else

while(temp!=NULL)

if(temp->data<num)

c++;

temp=temp->next;

if(c==0)

add(num);

else if(c<count())

addafter(num,++c);

else

append(num);

int delete(int num)

struct node *temp, *prev;

temp=head;

while(temp!=NULL)
{

if(temp->data==num)

if(temp==head)

head=temp->next;

free(temp);

return 1;

else

prev->next=temp->next

free(temp);

return 1;

else

prev=temp;

temp= temp->next;

return 0;

void display(struct node *r)

r=head;

if(r==NULL)
{

return;

while(r!=NULL)

printf("%d ",r->data);

r=r->next;

printf("\n");

int count()

struct node *n;

int c=0;

n=head;

while(n!=NULL)

n=n->next;

c++;

return c;

void main()

int i,num;

struct node *n;

head=NULL;

while(1)
{

printf("\nList Operations\n");

printf("===============\n");

printf("1.Insert\n");

printf("2.Display\n");

printf("3.Size\n");

printf("4.Delete\n");

printf("5.Exit\n");

printf("Enter your choice : ");

if(scanf("%d",&i)<=0){

printf("Enter only an Integer\n");

exit(0);

else{

switch(i)

case 1: printf("Enter the number to insert : ");

scanf("%d",&num);

insert(num);

break;

case 2: if(head==NULL)

printf("List is Empty\n");

else

Printf("Element(s) in the list are : ");

}
display(n);

break;

case 3: printf("Size of the list is %d\n",count());

break;

case 4: if(head==NULL)

printf("List is Empty\n");

else {

printf("Enter the number to delete : ");

scanf("%d",&num);

if(delete(num))

printf("%d deleted successfully\n",num);

else

printf("%d not found in the list\n",num);

break;

case 5: return 0;

default: printf("Invalid option\n");

}
5 b) Doubly Linked List with insertion, find, delete, add after, reverse, sort and display
operations Source Code

#include<malloc.h>

#include<stdio.h>

typedef struct lin_list

int data;

struct lin_list *llink,*rlink;

}node;

node *root,*temp,*new1;

int x;

node *creation()

temp = root = NULL;

printf("enter number (999 to stop)");

scanf("%d",&x);

while(x != 999)

new1 = (node *)malloc(sizeof(node));

new1->data = x;

new1->rlink = NULL;

new1->llink = NULL;

if(root == NULL)

root = new1;

temp->rlink = new1;

new1->llink = temp;

temp = new1;

printf("Enter data");
scanf("%d",&x);

return(root);

void display(node *root)

node *temp;

temp = root;

if(temp == NULL)

printf("list is empty");

return ;

printf("\nElements and address in list from left to right:");

while(temp != NULL)

printf("%2d %2u->",temp->data,temp);

temp =temp->rlink;

printf("NULL");

node *addatfirst(node *root)

new1 = (node *) malloc(sizeof(node));

printf("enter info");

scanf("%d",&new1->data);

new1->rlink = root;

root->llink = new1;
root = new1;

return root;

node *addatloc(node *root)

node *temp1;

int i=1,loc;

temp1 = root;

new1 = (node *)malloc(sizeof(node));

printf("enter the location to insert");

scanf("%d",&loc);

printf("enter info");

scanf("%d",&new1->data);

while(i!=loc-1)

temp1 = temp1->rlink;

i++;

new1->rlink = temp1->rlink;

new1->llink = temp1;

temp1->rlink=new1;

return root;

node *addatlast(node *root)

node *prev,*temp;

temp = root;

while(temp->rlink != NULL)
{

temp = temp->rlink;

new1 = (node *)malloc(sizeof(node));

printf("enter info");

scanf("%d",&new1->data);

temp->rlink = new1;

new1->llink = temp;

new1->rlink = NULL;

return root;

node *deleteatfirst(node *root)

node *temp;

temp = root;

printf("the deleted element is %d",temp->data);

root = temp->rlink;

free(temp);

return root;

node *deleteatloc(node *root)

int i,loc;

temp = root;

printf("enter the location to delete");

scanf("%d",&loc);

for(i=1;i<loc;i++)

{
temp = temp->rlink;

printf("the deleted element is %d",temp->data);

temp->llink->rlink = temp->rlink;

temp->rlink->llink = temp->llink;

free(temp);

return root;

node *deleteatlast(node *root)

node *prev,*temp;

prev = root;

temp = root;

if(temp == NULL)

printf("List is empty");

return 0;

while(temp->rlink != NULL)

prev = temp;

temp = temp->rlink;

printf("the deleted element is %d ",temp->data);

prev->rlink = NULL;

free(temp);

return root;

}
void search(node *root)

node *temp,*prev;

int item,flag=0;

temp = root;

printf("Enter an element tobe search");

scanf("%d",&item);

if(temp == NULL)

printf("List is empty");

while(temp->rlink != NULL)

if(temp->data == item)

flag = 1;

break;

else

temp = temp->rlink;

if(flag == 1)

printf("Element existed in list");

else

printf("Element not existed");

void main()
{

node *root,*head;

int ch,ch1;

clrscr();

printf(" ****Double linked list operations*** ");

do

printf("\n1:creation\n2:Insert\n3:Delete\n4:Display\n5.Search");

printf("\nEnter your choice");

scanf("%d",&ch);

switch(ch)

case 1: root = creation();

break;

case 2: clrscr();

printf("1:Add at first\n2:Add at given location\n3:Add at last");

printf("\nEnter your choice");

scanf("%d",&ch1);

switch(ch1)

case 1: root = addatfirst(root);

break;

case 2: root = addatloc(root);

break;

case 3: root = addatlast(root);

break;

}break;

case 3: clrscr();
printf("1:Delete at first\n2:Delete at given location\n3:Delete at last");

printf("Enter your choice");

scanf("%d",&ch1);

switch(ch1)

case 1: root = deleteatfirst(root);

break;

case 2: root = deleteatloc(root);

break;

case 3: root = deleteatlast(root);

break;

}break;

case 4: display(root);

break;

case 5: search(root);

break;

}while(ch<=5);

getch();

}
5 c) Circular Linked List with insertion, find, delete, add after, reverse, sort and
display operations Source Code

#include<bits/stdc++.h>

using namespace std;

struct Node

int data;

struct Node *next;

};

struct Node *addToEmpty(struct Node *last, int data)

// This function is only for empty list

if (last != NULL)

return last;

// Creating a node dynamically.

struct Node *temp =

(struct Node*)malloc(sizeof(struct Node));

// Assigning the data.

temp -> data = data;

last = temp;

// Creating the link.

last -> next = last;


return last;

struct Node *addBegin(struct Node *last, int data)

if (last == NULL)

return addToEmpty(last, data);

struct Node *temp =

(struct Node *)malloc(sizeof(struct Node));

temp -> data = data;

temp -> next = last -> next;

last -> next = temp;

return last;

struct Node *addEnd(struct Node *last, int data)

if (last == NULL)

return addToEmpty(last, data);

struct Node *temp =

(struct Node *)malloc(sizeof(struct Node));

temp -> data = data;

temp -> next = last -> next;


last -> next = temp;

last = temp;

return last;

struct Node *addAfter(struct Node *last, int data, int item)

if (last == NULL)

return NULL;

struct Node *temp, *p;

p = last -> next;

do

if (p ->data == item)

temp = (struct Node *)malloc(sizeof(struct Node));

temp -> data = data;

temp -> next = p -> next;

p -> next = temp;

if (p == last)

last = temp;

return last;

p = p -> next;

} while(p != last -> next);


cout << item << " not present in the list." << endl;

return last;

void traverse(struct Node *last)

struct Node *p;

// If list is empty, return.

if (last == NULL)

cout << "List is empty." << endl;

return;

// Pointing to first Node of the list.

p = last -> next;

// Traversing the list.

do

cout << p -> data << " ";

p = p -> next;

while(p != last->next);
}

// Driven Program

int main()

struct Node *last = NULL;

last = addToEmpty(last, 6);

last = addBegin(last, 4);

last = addBegin(last, 2);

last = addEnd(last, 8);

last = addEnd(last, 12);

last = addAfter(last, 10, 8);

traverse(last);

return 0;

}
6 a) Stack using Linked List Source code

#include <stdio.h>

#include <stdlib.h>

struct node

int info;

struct node *ptr;

}*top,*top1,*temp;

int topelement();

void push(int data);

void pop();

void empty();

void display();

void destroy();

void stack_count();

void create();

int count = 0;

void main()

int no, ch, e;

printf("\n 1 - Push");

printf("\n 2 - Pop");

printf("\n 3 - Top");

printf("\n 4 - Empty");

printf("\n 5 - Exit");

printf("\n 6 - Dipslay");

printf("\n 7 - Stack Count");

printf("\n 8 - Destroy stack");


create();

while (1)

printf("\n Enter choice : ");

scanf("%d", &ch);

switch (ch)

case 1:

printf("Enter data : ");

scanf("%d", &no);

push(no);

break;

case 2:

pop();

break;

case 3:

if (top == NULL)

printf("No elements in stack");

else

e = topelement();

printf("\n Top element : %d", e);

break;

case 4:

empty();

break;
case 5:

exit(0);

case 6:

display();

break;

case 7:

stack_count();

break;

case 8:

destroy();

break;

default :

printf(" Wrong choice, Please enter correct choice ");

break;

/* Create empty stack */

void create()

top = NULL;

/* Count stack elements */

void stack_count()

printf("\n No. of elements in stack : %d", count);

/* Push data into stack */


void push(int data)

if (top == NULL)

top =(struct node *)malloc(1*sizeof(struct node));

top->ptr = NULL;

top->info = data;

else

temp =(struct node *)malloc(1*sizeof(struct node));

temp->ptr = top;

temp->info = data;

top = temp;

count++;

/* Display stack elements */

void display()

top1 = top;

if (top1 == NULL)

printf("Stack is empty");

return;

while (top1 != NULL)

{
printf("%d ", top1->info);

top1 = top1->ptr;

/* Pop Operation on stack */

void pop()

top1 = top;

if (top1 == NULL)

printf("\n Error : Trying to pop from empty stack");

return;

else

top1 = top1->ptr;

printf("\n Popped value : %d", top->info);

free(top);

top = top1;

count--;

/* Return top element */

int topelement()

return(top->info);

/* Check if stack is empty or not */

void empty()

{
if (top == NULL)

printf("\n Stack is empty");

else

printf("\n Stack is not empty with %d elements",count);

/* Destroy entire stack */

void destroy()

top1 = top;

while (top1 != NULL)

top1 = top->ptr;

free(top);

top = top1;

top1 = top1->ptr;

free(top1);

top = NULL;

printf("\n All stack elements destroyed");

count = 0;

}
6 b) Stack using two Queues Source code

#include <stdio.h>

#include <stdlib.h>

/* Queue structure */

#define QUEUE_EMPTY_MAGIC 0xdeadbeef

typedef struct _queue_t {

int *arr;

int rear, front, count, max;

} queue_t;

/* Queue operation function prototypes */

queue_t *queue_allocate(int n);

void queue_insert(queue_t * q, int v);

int queue_remove(queue_t * q);

int queue_count(queue_t * q);

int queue_is_empty(queue_t * q);

/* NOTE: Here is the stuff we are interested in */

/* Simulated stack operations START */

/* NOTE: passing the queue object, on which we will only operate the

* queue operations.

*/

void stack_push(queue_t * q, int v) {

queue_insert(q, v);
}

int stack_pop(queue_t * q) {

int i, n = queue_count(q);

int removed_element;

for (i = 0; i < (n - 1); i++) {

removed_element = queue_remove(q);

queue_insert(q, removed_element);

/* same as below */

//queue_insert (q, queue_remove (q))

removed_element = queue_remove(q);

return removed_element;

int stack_is_empty(queue_t * q) {

return queue_is_empty(q);

int stack_count(queue_t * q) {

return queue_count(q);

/* Simulated stack operations END */

/* Queue operations START */


int queue_count(queue_t * q) {

return q->count;

queue_t *

queue_allocate(int n) {

queue_t *queue;

queue = malloc(sizeof(queue_t));

if (queue == NULL)

return NULL;

queue->max = n;

queue->arr = malloc(sizeof(int) * n);

queue->rear = n - 1;

queue->front = n - 1;

return queue;

void queue_insert(queue_t * q, int v) {

if (q->count == q->max)

return;

q->rear = (q->rear + 1) % q->max;

q->arr[q->rear] = v;

q->count++;
}

int queue_remove(queue_t * q) {

int retval;

/* magic number if queue is empty */

if (q->count == 0)

return QUEUE_EMPTY_MAGIC;

q->front = (q->front + 1) % q->max;

retval = q->arr[q->front];

q->count--;

return retval;

int queue_is_empty(queue_t * q) {

return (q->count == 0);

/* Queue operations END */

/* For demo */

void queue_display(queue_t * q) {

int i = (q->front + 1) % q->max, elements = queue_count(q);

while (elements--) {

printf("[%d], ", q->arr[i]);


i = (i >= q->max) ? 0 : (i + 1);

#define MAX 128

int main(void) {

queue_t *q;

int x, select;

/* Static allocation */

q = queue_allocate(MAX);

do {

printf("\n[1] Push\n[2] Pop\n[0] Exit");

printf("\nChoice: ");

scanf(" %d", &select);

switch (select) {

case 1:

printf("\nEnter value to Push:");

scanf(" %d", &x);

/* Pushing */

stack_push(q, x);

printf("\n\n__________________________\nCurrent Queue:\n");

queue_display(q);

printf("\n\nPushed Value: %d", x);


printf("\n__________________________\n");

break;

case 2:

/* Popping */

x = stack_pop(q);

printf("\n\n\n\n__________________________\nCurrent Queue:\n");

queue_display(q);

if (x == QUEUE_EMPTY_MAGIC)

printf("\n\nNo values removed");

else

printf("\n\nPopped Value: %d", x);

printf("\n__________________________\n");

break;

case 0:

printf("\nQutting.\n");

return 0;

default:

printf("\nQutting.\n");

return 0;

} while (1);
return 0;

$ gcc StackUsingQueue.c

$ ./a.out

[1] Push

[2] Pop

[0] Exit

Choice: 1

Enter value to Push: 12

__________________________

Current Queue:

[12],

Pushed Value: 12

__________________________

[1] Push

[2] Pop

[0] Exit

Choice: 1

Enter value to Push: 53

__________________________

Current Queue:

[12], [53],

Pushed Value: 53

_____________________
6 c) Source Code Towers of Hanoi

#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)

if (n == 1)

printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);

return;

towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);

towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

int main()

int n = 4; // Number of disks

towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods

return 0;

Output

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 3 from rod A to rod B

Move disk 1 from rod C to rod A

Move disk 2 from rod C to rod B

Move disk 1 from rod A to rod B


Move disk 4 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 2 from rod B to rod A

Move disk 1 from rod C to rod A

Move disk 3 from rod B to rod C

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C


7 a) Circular Queue (array implementation)

#include<bits/stdc++.h>

using namespace std;

struct Queue

// Initialize front and rear

int rear, front;

// Circular Queue

int size;

int *arr;

Queue(int s)

front = rear = -1;

size = s;

arr = new int[s];

void enQueue(int value);

int deQueue();

void displayQueue();

};

/* Function to create Circular queue */

void Queue::enQueue(int value)

if ((front == 0 && rear == size-1) ||

(rear == (front-1)%(size-1)))
{

printf("\nQueue is Full");

return;

else if (front == -1) /* Insert First Element */

front = rear = 0;

arr[rear] = value;

else if (rear == size-1 && front != 0)

rear = 0;

arr[rear] = value;

else

rear++;

arr[rear] = value;

// Function to delete element from Circular Queue

int Queue::deQueue()

if (front == -1)
{

printf("\nQueue is Empty");

return INT_MIN;

int data = arr[front];

arr[front] = -1;

if (front == rear)

front = -1;

rear = -1;

else if (front == size-1)

front = 0;

else

front++;

return data;

// Function displaying the elements

// of Circular Queue

void Queue::displayQueue()

if (front == -1)

printf("\nQueue is Empty");

return;
}

printf("\nElements in Circular Queue are: ");

if (rear >= front)

for (int i = front; i <= rear; i++)

printf("%d ",arr[i]);

else

for (int i = front; i < size; i++)

printf("%d ", arr[i]);

for (int i = 0; i <= rear; i++)

printf("%d ", arr[i]);

/* Driver of the program */

int main()

Queue q(5);

// Inserting elements in Circular Queue

q.enQueue(14);

q.enQueue(22);

q.enQueue(13);

q.enQueue(-6);
// Display elements present in Circular Queue

q.displayQueue();

// Deleting elements from Circular Queue

printf("\nDeleted value = %d", q.deQueue());

printf("\nDeleted value = %d", q.deQueue());

q.displayQueue();

q.enQueue(9);

q.enQueue(20);

q.enQueue(5);

q.displayQueue();

q.enQueue(20);

return 0;

Output:

Elements in Circular Queue are: 14 22 13 -6

Deleted value = 14

Deleted value = 22

Elements in Circular Queue are: 13 -6

Elements in Circular Queue are: 13 -6 9 20 5

Queue is Full
7 B). Queue using Linked List

// A C program to demonstrate linked list based implementation of queue

#include <stdlib.h>

#include <stdio.h>

// A linked list (LL) node to store a queue entry

struct QNode

int key;

struct QNode *next;

};

// The queue, front stores the front node of LL and rear stores ths

// last node of LL

struct Queue

struct QNode *front, *rear;

};

// A utility function to create a new linked list node.

struct QNode* newNode(int k)

struct QNode *temp = (struct QNode*)malloc(sizeof(struct QNode));

temp->key = k;

temp->next = NULL;

return temp;

}
// A utility function to create an empty queue

struct Queue *createQueue()

struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));

q->front = q->rear = NULL;

return q;

// The function to add a key k to q

void enQueue(struct Queue *q, int k)

// Create a new LL node

struct QNode *temp = newNode(k);

// If queue is empty, then new node is front and rear both

if (q->rear == NULL)

q->front = q->rear = temp;

return;

// Add the new node at the end of queue and change rear

q->rear->next = temp;

q->rear = temp;

// Function to remove a key from given queue q


struct QNode *deQueue(struct Queue *q)

// If queue is empty, return NULL.

if (q->front == NULL)

return NULL;

// Store previous front and move front one node ahead

struct QNode *temp = q->front;

q->front = q->front->next;

// If front becomes NULL, then change rear also as NULL

if (q->front == NULL)

q->rear = NULL;

return temp;

// Driver Program to test anove functions

int main()

struct Queue *q = createQueue();

enQueue(q, 10);

enQueue(q, 20);

deQueue(q);

deQueue(q);

enQueue(q, 30);

enQueue(q, 40);

enQueue(q, 50);

struct QNode *n = deQueue(q);


if (n != NULL)

printf("Dequeued item is %d", n->key);

return 0;

Output:

Dequeued item is 30
7 C. Queue using two stacks

* C program to implement queues using two stacks */

#include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node *next;

};

void push(struct node** top, int data);

int pop(struct node** top);

struct queue

struct node *stack1;

struct node *stack2;

};

void enqueue(struct queue *q, int x)

push(&q->stack1, x);

void dequeue(struct queue *q)

int x;

if (q->stack1 == NULL && q->stack2 == NULL) {

printf("queue is empty");

return;

if (q->stack2 == NULL) {
while (q->stack1 != NULL) {

x = pop(&q->stack1);

push(&q->stack2, x);

x = pop(&q->stack2);

printf("%d\n", x);

void push(struct node** top, int data)

struct node* newnode = (struct node*) malloc(sizeof(struct node));

if (newnode == NULL) {

printf("Stack overflow \n");

return;

newnode->data = data;

newnode->next = (*top);

(*top) = newnode;

int pop(struct node** top)

int buff;

struct node *t;

if (*top == NULL) {

printf("Stack underflow \n");

return;

else {
t = *top;

buff = t->data;

*top = t->next;

free(t);

return buff;

void display(struct node *top1,struct node *top2)

while (top1 != NULL) {

printf("%d\n", top1->data);

top1 = top1->next;

while (top2 != NULL) {

printf("%d\n", top2->data);

top2 = top2->next;

int main()

struct queue *q = (struct queue*)malloc(sizeof(struct queue));

int f = 0, a;

char ch = 'y';

q->stack1 = NULL;

q->stack2 = NULL;

while (ch == 'y'||ch == 'Y') {

printf("enter ur choice\n1.add to queue\n2.remove

from queue\n3.display\n4.exit\n");
scanf("%d", &f);

switch(f) {

case 1 : printf("enter the element to be added to queue\n");

scanf("%d", &a);

enqueue(q, a);

break;

case 2 : dequeue(q);

break;

case 3 : display(q->stack1, q->stack2);

break;

case 4 : exit(1);

break;

default : printf("invalid\n");

break;

Output

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

Enter the element to be added to queue

34

Enter your choice

1. Add an element to the queue


2. Remove an element from queue

3. Display the elements in queue

4. Exit

Enter the element to be added to queue

55

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

Enter the element to be added to queue

99

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

Enter the element to be added to queue

77

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

3
34

55

99

77

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit

55

99

77

Enter your choice

1. Add an element to the queue

2. Remove an element from queue

3. Display the elements in queue

4. Exit
8 a) Balanced Brackets

#include < stdio.h >

#include < conio.h >

#define max 50

void main()

char stk[max],exp[100];

int top,i;

clrscr();

top = -1;

printf("\nEnter an infix expression ");

gets(exp);

for(i=0; exp[i] != '\0'; i++)

if( exp[i]=='(' || exp[i] =='[' || exp[i] == '{' )

top++;

stk[top]= exp[i];

else

if ( exp[i] == ')' )

if( stk[top] == '(' )

top--;

else

printf("Unbalanced exp");
exit(0);

else

if ( exp[i] == ']' )

if( stk[top] == '[' )

top--;

else

printf("Unbalanced exp");

exit(0);

else

if ( exp[i] == '}' )

if( stk[top] == '{' )

top--;

else

printf("Unbalanced exp");

exit(0);

} // for

if( top == -1 )

printf("Exp is balanced");
else

printf("Exp is not balanced");

} // main

Output:
Exp is Balanced
8 B).Infix to Postfix

#include<stdio.h>

char stack[20];

int top = -1;

void push(char x)

stack[++top] = x;

char pop()

if(top == -1)

return -1;

else

return stack[top--];

int priority(char x)

if(x == '(')

return 0;

if(x == '+' || x == '-')

return 1;

if(x == '*' || x == '/')

return 2;

main()

{
char exp[20];

char *e, x;

printf("Enter the expression :: ");

scanf("%s",exp);

e = exp;

while(*e != '\0')

if(isalnum(*e))

printf("%c",*e);

else if(*e == '(')

push(*e);

else if(*e == ')')

while((x = pop()) != '(')

printf("%c", x);

else

while(priority(stack[top]) >= priority(*e))

printf("%c",pop());

push(*e);

e++;

while(top != -1)

printf("%c",pop());

}
OUTPUT:

Enter the expression :: a+b*c

abc*+

Enter the expression :: (a+b)*c+(d-a)

ab+c*da-+
8 C). Evaluation of Postfix

#include<stdio.h>

int stack[20];

int top = -1;

void push(int x)

stack[++top] = x;

int pop()

return stack[top--];

int main()

char exp[20];

char *e;

int n1,n2,n3,num;

printf("Enter the expression :: ");

scanf("%s",exp);

e = exp;

while(*e != '\0')

if(isdigit(*e))

num = *e - 48;

push(num);
}

else

n1 = pop();

n2 = pop();

switch(*e)

case '+':

n3 = n1 + n2;

break;

case '-':

n3 = n2 - n1;

break;

case '*':

n3 = n1 * n2;

break;

case '/':

n3 = n2 / n1;

break;

push(n3);

}
e++;

printf("\nThe result of expression %s = %d\n\n",exp,pop());

return 0;

OUTPUT:
Enter the expression :: 245+*

The result of expression 245+* = 18


9 a) C program to find maximum and minimum in a Bianry Tree

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

// A tree node

struct Node

int data;

struct Node* left, *right;

};

// A utility function to create a new node

struct Node* newNode(int data)

struct Node* node = (struct Node*)

malloc(sizeof(struct Node));

node->data = data;

node->left = node->right = NULL;

return(node);

// Returns maximum value in a given Binary Tree

int findMax(struct Node* root)

// Base case

if (root == NULL)

return INT_MIN;
// Return maximum of 3 values:

// 1) Root's data 2) Max in Left Subtree

// 3) Max in right subtree

int res = root->data;

int lres = findMax(root->left);

int rres = findMax(root->right);

if (lres > res)

res = lres;

if (rres > res)

res = rres;

return res;

// Driver program

int main(void)

struct Node*NewRoot=NULL;

struct Node *root = newNode(2);

root->left = newNode(7);

root->right = newNode(5);

root->left->right = newNode(6);

root->left->right->left=newNode(1);

root->left->right->right=newNode(11);

root->right->right=newNode(9);

root->right->right->left=newNode(4);

printf ("Maximum element is %d \n", findMax(root));


return 0;

Output:

Maximum element is 11

// Returns minimum value in a given Binary Tree

int findMin(struct Node* root)

// Base case

if (root == NULL)

return INT_MAX;

// Return minimum of 3 values:

// 1) Root's data 2) Max in Left Subtree

// 3) Max in right subtree

int res = root->data;

int lres = findMin(root->left);

int rres = findMin(root->right);

if (lres < res)

res = lres;

if (rres < res)

res = rres;

return res;

// C program to demonstrate insert operation in binary search tree

#include<stdio.h>
#include<stdlib.h>

struct node

int key;

struct node *left, *right;

};

// A utility function to create a new BST node

struct node *newNode(int item)

struct node *temp = (struct node *)malloc(sizeof(struct node));

temp->key = item;

temp->left = temp->right = NULL;

return temp;

// A utility function to do inorder traversal of BST

void inorder(struct node *root)

if (root != NULL)

inorder(root->left);

printf("%d \n", root->key);

inorder(root->right);

}
/* A utility function to insert a new node with given key in BST */

struct node* insert(struct node* node, int key)

/* If the tree is empty, return a new node */

if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

/* return the (unchanged) node pointer */

return node;

// Driver Program to test above functions

int main()

/* Let us create following BST

50

/ \

30 70

/ \ / \

20 40 60 80 */

struct node *root = NULL;

root = insert(root, 50);

insert(root, 30);
insert(root, 20);

insert(root, 40);

insert(root, 70);

insert(root, 60);

insert(root, 80);

// print inoder traversal of the BST

inorder(root);

return 0;

Output:

20

30

40

50

60

70

80
9 b)BST- Delete, Inorder, Preorder, Postorder traversal

/*

* C Program to Construct a Binary Search Tree and perform deletion, inorder traversal on it

*/

#include <stdio.h>

#include <stdlib.h>

struct btnode

int value;

struct btnode *l;

struct btnode *r;

}*root = NULL, *temp = NULL, *t2, *t1;

void delete1();

void insert();

void delete();

void inorder(struct btnode *t);

void create();

void search(struct btnode *t);

void preorder(struct btnode *t);

void postorder(struct btnode *t);

void search1(struct btnode *t,int data);

int smallest(struct btnode *t);

int largest(struct btnode *t);

int flag = 1;
void main()

int ch;

printf("\nOPERATIONS ---");

printf("\n1 - Insert an element into tree\n");

printf("2 - Delete an element from the tree\n");

printf("3 - Inorder Traversal\n");

printf("4 - Preorder Traversal\n");

printf("5 - Postorder Traversal\n");

printf("6 - Exit\n");

while(1)

printf("\nEnter your choice : ");

scanf("%d", &ch);

switch (ch)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:

inorder(root);

break;

case 4:

preorder(root);
break;

case 5:

postorder(root);

break;

case 6:

exit(0);

default :

printf("Wrong choice, Please enter correct choice ");

break;

/* To insert a node in the tree */

void insert()

create();

if (root == NULL)

root = temp;

else

search(root);

/* To create a node */

void create()

int data;
printf("Enter data of node to be inserted : ");

scanf("%d", &data);

temp = (struct btnode *)malloc(1*sizeof(struct btnode));

temp->value = data;

temp->l = temp->r = NULL;

/* Function to search the appropriate position to insert the new node */

void search(struct btnode *t)

if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at
right */

search(t->r);

else if ((temp->value > t->value) && (t->r == NULL))

t->r = temp;

else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at
left */

search(t->l);

else if ((temp->value < t->value) && (t->l == NULL))

t->l = temp;

/* recursive function to perform inorder traversal of tree */

void inorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;
}

if (t->l != NULL)

inorder(t->l);

printf("%d -> ", t->value);

if (t->r != NULL)

inorder(t->r);

/* To check for the deleted node */

void delete()

int data;

if (root == NULL)

printf("No elements in a tree to delete");

return;

printf("Enter the data to be deleted : ");

scanf("%d", &data);

t1 = root;

t2 = root;

search1(root, data);

/* To find the preorder traversal */

void preorder(struct btnode *t)

{
if (root == NULL)

printf("No elements in a tree to display");

return;

printf("%d -> ", t->value);

if (t->l != NULL)

preorder(t->l);

if (t->r != NULL)

preorder(t->r);

/* To find the postorder traversal */

void postorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display ");

return;

if (t->l != NULL)

postorder(t->l);

if (t->r != NULL)

postorder(t->r);

printf("%d -> ", t->value);

/* Search for the appropriate position to insert the new node */


void search1(struct btnode *t, int data)

if ((data>t->value))

t1 = t;

search1(t->r, data);

else if ((data < t->value))

t1 = t;

search1(t->l, data);

else if ((data==t->value))

delete1(t);

/* To delete a node */

void delete1(struct btnode *t)

int k;

/* To delete leaf node */

if ((t->l == NULL) && (t->r == NULL))

if (t1->l == t)

{
t1->l = NULL;

else

t1->r = NULL;

t = NULL;

free(t);

return;

/* To delete node having one left hand child */

else if ((t->r == NULL))

if (t1 == t)

root = t->l;

t1 = root;

else if (t1->l == t)

t1->l = t->l;

else

t1->r = t->l;

}
t = NULL;

free(t);

return;

/* To delete node having right hand child */

else if (t->l == NULL)

if (t1 == t)

root = t->r;

t1 = root;

else if (t1->r == t)

t1->r = t->r;

else

t1->l = t->r;

t == NULL;

free(t);

return;

/* To delete node having two child */

else if ((t->l != NULL) && (t->r != NULL))

t2 = root;

if (t->r != NULL)

{
k = smallest(t->r);

flag = 1;

else

k =largest(t->l);

flag = 2;

search1(root, k);

t->value = k;

/* To find the smallest element in the right sub tree */

int smallest(struct btnode *t)

t2 = t;

if (t->l != NULL)

t2 = t;

return(smallest(t->l));

else

return (t->value);

/* To find the largest element in the left sub tree */


int largest(struct btnode *t)

if (t->r != NULL)

t2 = t;

return(largest(t->r));

else

return(t->value);

OPERATIONS ---

1 - Insert an element into tree

2 - Delete an element from the tree

3 - Inorder Traversal

4 - Preorder Traversal

5 - Postorder Traversal

6 - Exit

Enter your choice : 1

Enter data of node to be inserted : 40

Enter your choice : 1

Enter data of node to be inserted : 20

Enter your choice : 1

Enter data of node to be inserted : 10


Enter your choice : 1

Enter data of node to be inserted : 30

Enter your choice : 1

Enter data of node to be inserted : 60

Enter your choice : 1

Enter data of node to be inserted : 80

Enter your choice : 1

Enter data of node to be inserted : 90

Enter your choice : 3

10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

40

/\

/ \

20 60

/\ \

10 30 80

90
9 C.Expression tree

#include<STDIO.H>
#include<CONIO.H>
#include<MALLOC.H>
typedef struct tree
{
char data;
struct tree *left;
struct tree *right;
}*pos;
pos stack[30];
int top=-1;
pos newnode(char b)
{
pos temp;
temp=(struct tree*)malloc(sizeof(struct tree));
temp->data=b;
temp->left=NULL;
temp->right=NULL;
return(temp);
}
void push(pos temp)
{
stack[++top]=temp;
}
pos pop()
{
pos p;
p=stack[top--];
return(p);
}
void inorder(pos t)
{
if(t!=NULL)
{
inorder(t->left);
printf(“%s”,t->data);
inorder(t->right);
}
}
void preorder(pos t)
{
if(t!=NULL)
{
printf(“%s”,t->data);
preorder(t->left);
inorder(t->right);
}
}
void postorder(pos t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf(“%s”,t->data);
}
}
void main()
{
char a[20];pos temp,t;int j,i;
clrscr();
printf(“\nEnter the postfix expression”);
gets(a);
for(i=0;a[i]!=NULL;i++)
{
if(a[i]==’*’ || a[i]==’/’ || a[i]==’+’ || a[i]==’-')
{
temp=newnode(a[i]);
temp->right=pop();
temp->left=pop();
push(temp);
}
else
{
temp=newnode(a[i]);
push(temp);
}
}
inorder(temp);
printf(“\n”);
preorder(temp);
printf(“\n”);
postorder(temp);
getch();
}
10 a) C program to insert a node in AVL tree

#include<stdio.h>

#include<stdlib.h>

// An AVL tree node

struct Node

int key;

struct Node *left;

struct Node *right;

int height;

};

// A utility function to get maximum of two integers

int max(int a, int b);

// A utility function to get the height of the tree

int height(struct Node *N)

if (N == NULL)

return 0;

return N->height;

// A utility function to get maximum of two integers

int max(int a, int b)

return (a > b)? a : b;


}

/* Helper function that allocates a new node with the given key and

NULL left and right pointers. */

struct Node* newNode(int key)

struct Node* node = (struct Node*)

malloc(sizeof(struct Node));

node->key = key;

node->left = NULL;

node->right = NULL;

node->height = 1; // new node is initially added at leaf

return(node);

// A utility function to right rotate subtree rooted with y

// See the diagram given above.

struct Node *rightRotate(struct Node *y)

struct Node *x = y->left;

struct Node *T2 = x->right;

// Perform rotation

x->right = y;

y->left = T2;

// Update heights

y->height = max(height(y->left), height(y->right))+1;


x->height = max(height(x->left), height(x->right))+1;

// Return new root

return x;

// A utility function to left rotate subtree rooted with x

// See the diagram given above.

struct Node *leftRotate(struct Node *x)

struct Node *y = x->right;

struct Node *T2 = y->left;

// Perform rotation

y->left = x;

x->right = T2;

// Update heights

x->height = max(height(x->left), height(x->right))+1;

y->height = max(height(y->left), height(y->right))+1;

// Return new root

return y;

// Get Balance factor of node N

int getBalance(struct Node *N)

{
if (N == NULL)

return 0;

return height(N->left) - height(N->right);

// Recursive function to insert a key in the subtree rooted

// with node and returns the new root of the subtree.

struct Node* insert(struct Node* node, int key)

/* 1. Perform the normal BST insertion */

if (node == NULL)

return(newNode(key));

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

else // Equal keys are not allowed in BST

return node;

/* 2. Update height of this ancestor node */

node->height = 1 + max(height(node->left),

height(node->right));

/* 3. Get the balance factor of this ancestor

node to check whether this node became

unbalanced */

int balance = getBalance(node);


// If this node becomes unbalanced, then

// there are 4 cases

// Left Left Case

if (balance > 1 && key < node->left->key)

return rightRotate(node);

// Right Right Case

if (balance < -1 && key > node->right->key)

return leftRotate(node);

// Left Right Case

if (balance > 1 && key > node->left->key)

node->left = leftRotate(node->left);

return rightRotate(node);

// Right Left Case

if (balance < -1 && key < node->right->key)

node->right = rightRotate(node->right);

return leftRotate(node);

/* return the (unchanged) node pointer */

return node;
}

// A utility function to print preorder traversal

// of the tree.

// The function also prints height of every node

void preOrder(struct Node *root)

if(root != NULL)

printf("%d ", root->key);

preOrder(root->left);

preOrder(root->right);

/* Drier program to test above function*/

int main()

struct Node *root = NULL;

/* Constructing tree given in the above figure */

root = insert(root, 10);

root = insert(root, 20);

root = insert(root, 30);

root = insert(root, 40);

root = insert(root, 50);

root = insert(root, 25);


/* The constructed AVL Tree would be

30

/ \

20 40

/ \ \

10 25 50

*/

printf("Preorder traversal of the constructed AVL"

" tree is \n");

preOrder(root);

return 0;

}
11 a)Hash Table with chaining

#include <stdio.h>

#include<stdlib.h>

#define MAX 20

struct Employee

int employee_id;

char employee_name[45];

int employee_age;

};

struct Record

struct Employee data;

struct Record *link;

};

void insert(struct Employee employee_record, struct Record *hash_table[]);

int search_element(int key, struct Record *hash_table[]);

void remove_record(int key, struct Record *hash_table[]);

void show(struct Record *hash_table[]);

int hash_function(int key);

int main()

struct Record *hash_table[MAX];

struct Employee employee_record;

int count, key, option;


for(count = 0; count <= MAX - 1; count++)

hash_table[count] = NULL;

while(1)

printf("1. Insert a Record in Hash Table\n");

printf("2. Search for a Record\n");

printf("3. Delete a Record\n");

printf("4. Show Hash Table\n");

printf("5. Quit\n");

printf("Enter your option\n");

scanf("%d",&option);

switch(option)

case 1:

printf("Enter the Employee Details\n");

printf("Employee ID:\t");

scanf("%d", &employee_record.employee_id);

printf("Employee Name:\t");

scanf("%s", employee_record.employee_name);

printf("Employee Age:\t");

scanf("%d", &employee_record.employee_age);

insert(employee_record, hash_table);

break;

case 2:

printf("Enter the element to search:\t");

scanf("%d", &key);
count = search_element(key, hash_table);

if(count == -1)

printf("Element Not Found\n");

else

printf("Element Found in Chain:\t%d\n", count);

break;

case 3:

printf("Enter the element to delete:\t");

scanf("%d", &key);

remove_record(key, hash_table);

break;

case 4:

show(hash_table);

break;

case 5:

exit(1);

return 0;

void insert(struct Employee employee_record, struct Record *hash_table[])

int key, h;
struct Record *temp;

key = employee_record.employee_id;

if(search_element(key, hash_table) != -1)

printf("Duplicate Key\n");

return;

h = hash_function(key);

temp = malloc(sizeof(struct Record));

temp->data = employee_record;

temp->link = hash_table[h];

hash_table[h] = temp;

void show(struct Record *hash_table[])

int count;

struct Record *ptr;

for(count = 0; count < MAX; count++)

printf("\n[%3d]", count);

if(hash_table[count] != NULL)

ptr = hash_table[count];

while(ptr != NULL)

printf("%d %s %d\t", ptr->data.employee_id, ptr->data.employee_name, ptr-


>data.employee_age);

ptr=ptr->link;
}

printf("\n");

int search_element(int key, struct Record *hash_table[])

int h;

struct Record *ptr;

h = hash_function(key);

ptr = hash_table[h];

while(ptr != NULL)

if(ptr->data.employee_id == key)

return h;

ptr = ptr->link;

return -1;

void remove_record(int key, struct Record *hash_table[])

int h;

struct Record *temp, *ptr;

h = hash_function(key);
if(hash_table[h]==NULL)

printf("Key %d Not Found\n", key);

return;

if(hash_table[h]->data.employee_id == key)

temp = hash_table[h];

hash_table[h] = hash_table[h]->link;

free(temp);

return;

ptr = hash_table[h];

while(ptr->link != NULL)

if(ptr->link->data.employee_id == key)

temp = ptr->link;

ptr->link = temp->link;

free(temp);

return;

ptr = ptr->link;

printf("Key %d Not Found\n", key);

int hash_function(int key)


{

return (key % MAX);

}
11 b) Open Addressing Hash Table with Quadratic probing and rehashing.

#include<stdio.h>

include<stdlib.h>

/* to store a data (consisting of key and value) in hash table array */

struct item

int key;

int value;

};

/* each hash table item has a flag (status) and data (consisting of key and value) */

struct hashtable_item

int flag;

/*

* flag = 0 : data does not exist

* flag = 1 : data exists at given array location

* flag = 2 : data was present at least once

*/

struct item *data;

};

struct hashtable_item *array;

int size = 0;

int max = 10;


/* this function returns corresponding index of the given key */

int hashcode(int key)

return (key % max);

/* this function initializes the hash table array */

void init_array()

int i;

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

array[i].flag = 0;

array[i].data = NULL;

/* this function inserts an element in the hash table */

void insert(int key, int value)

int index = hashcode(key);

int i = index;

int h = 1;

struct item *new_item = (struct item*) malloc(sizeof(struct item));

new_item->key = key;
new_item->value = value;

/* probing through the array until an empty space is found */

while (array[i].flag == 1)

if (array[i].data->key == key)

/* case when already present key matches the given key */

printf("\n This key is already present in hash table, hence updating it's value \n");

array[i].data->value = value;

return;

i = (i + (h * h)) % max;

h++;

if (i == index)

printf("\n Hash table is full, cannot add more elements \n");

return;

array[i].flag = 1;

array[i].data = new_item;

printf("\n Key (%d) has been inserted\n", key);


size++;

/* to remove an element form the hash table array */

void remove_element(int key)

int index = hashcode(key);

int i = index;

int h = 1;

/* probing through the hash table until we reach at location where there had not been an element even
once */

while (array[i].flag != 0)

if (array[i].flag == 1 && array[i].data->key == key)

/* case where data exists at the location and its key matches to the given
key*/

array[i].flag = 2;

array[i].data = NULL;

size--;

printf("\n Key (%d) has been removed \n", key);

return;

i = (i + (h * h)) % max;
h++;

if (i == index)

break;

printf("\n Key does not exist \n");

/* to display the contents of hash table */

void display()

int i;

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

if (array[i].flag != 1)

printf("\n Array[%d] has no elements \n", i);

else

printf("\n Array[%d] has elements \n %d (key) and%d (value) \n", i, array[i].data-


>key, array[i].data->value);

}
int size_of_hashtable()

return size;

void main()

int choice, key, value, n, c;

clrscr();

array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));

init_array();

do {

printf("Implementation of Hash Table in C with Quadratic

Probing.\n\n");

printf("MENU-: \n1.Inserting item in the Hash table"

"\n2.Removing item from the Hash table"

"\n3.Check the size of Hash table"

"\n4.Display Hash table"

"\n\n Please enter your choice-:");

scanf("%d", &choice);

switch(choice)

{
case 1:

printf("Inserting element in Hash table \n");

printf("Enter key and value-:\t");

scanf("%d %d", &key, &value);

insert(key, value);

break;

case 2:

printf("Deleting in Hash table \n Enter the key to delete-:");

scanf("%d", &key);

remove_element(key);

break;

case 3:

n = size_of_hashtable();

printf("Size of Hash table is-:%d\n", n);

break;

case 4:

display();
break;

default:

printf("Wrong Input\n");

printf("\n Do you want to continue-:(press 1 for yes)\t");

scanf("%d", &c);

}while(c == 1);

getch();

}
12 a) Build Heap

// A C++ program to demonstrate common Binary Heap Operations

#include<iostream>

#include<climits>

using namespace std;

// Prototype of a utility function to swap two integers

void swap(int *x, int *y);

// A class for Min Heap

class MinHeap

int *harr; // pointer to array of elements in heap

int capacity; // maximum possible size of min heap

int heap_size; // Current number of elements in min heap

public:

// Constructor

MinHeap(int capacity);

// to heapify a subtree with the root at given index

void MinHeapify(int );

int parent(int i) { return (i-1)/2; }

// to get index of left child of node at index i

int left(int i) { return (2*i + 1); }

// to get index of right child of node at index i


int right(int i) { return (2*i + 2); }

// to extract the root which is the minimum element

int extractMin();

// Decreases key value of key at index i to new_val

void decreaseKey(int i, int new_val);

// Returns the minimum key (key at root) from min heap

int getMin() { return harr[0]; }

// Deletes a key stored at index i

void deleteKey(int i);

// Inserts a new key 'k'

void insertKey(int k);

};

// Constructor: Builds a heap from a given array a[] of given size

MinHeap::MinHeap(int cap)

heap_size = 0;

capacity = cap;

harr = new int[cap];

// Inserts a new key 'k'

void MinHeap::insertKey(int k)
{

if (heap_size == capacity)

cout << "\nOverflow: Could not insertKey\n";

return;

// First insert the new key at the end

heap_size++;

int i = heap_size - 1;

harr[i] = k;

// Fix the min heap property if it is violated

while (i != 0 && harr[parent(i)] > harr[i])

swap(&harr[i], &harr[parent(i)]);

i = parent(i);

// Decreases value of key at index 'i' to new_val. It is assumed that

// new_val is smaller than harr[i].

void MinHeap::decreaseKey(int i, int new_val)

harr[i] = new_val;

while (i != 0 && harr[parent(i)] > harr[i])

swap(&harr[i], &harr[parent(i)]);
i = parent(i);

// Method to remove minimum element (or root) from min heap

int MinHeap::extractMin()

if (heap_size <= 0)

return INT_MAX;

if (heap_size == 1)

heap_size--;

return harr[0];

// Store the minimum value, and remove it from heap

int root = harr[0];

harr[0] = harr[heap_size-1];

heap_size--;

MinHeapify(0);

return root;

// This function deletes key at index i. It first reduced value to minus

// infinite, then calls extractMin()

void MinHeap::deleteKey(int i)
{

decreaseKey(i, INT_MIN);

extractMin();

// A recursive method to heapify a subtree with the root at given index

// This method assumes that the subtrees are already heapified

void MinHeap::MinHeapify(int i)

int l = left(i);

int r = right(i);

int smallest = i;

if (l < heap_size && harr[l] < harr[i])

smallest = l;

if (r < heap_size && harr[r] < harr[smallest])

smallest = r;

if (smallest != i)

swap(&harr[i], &harr[smallest]);

MinHeapify(smallest);

// A utility function to swap two elements

void swap(int *x, int *y)

int temp = *x;

*x = *y;
*y = temp;

// Driver program to test above functions

int main()

MinHeap h(11);

h.insertKey(3);

h.insertKey(2);

h.deleteKey(1);

h.insertKey(15);

h.insertKey(5);

h.insertKey(4);

h.insertKey(45);

cout << h.extractMin() << " ";

cout << h.getMin() << " ";

h.decreaseKey(2, 1);

cout << h.getMin();

return 0;

Percolate up, Percolate Down, Heap sort


13 a) Breadth First Search

#include<stdio.h>

int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;

void bfs(int v) {

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

if(a[v][i] && !visited[i])

q[++r] = i;

if(f <= r) {

visited[q[f]] = 1;

bfs(q[f++]);

void main() {

int v;

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

scanf("%d", &n);

for(i=1; i <= n; i++) {

q[i] = 0;

visited[i] = 0;

printf("\n Enter graph data in matrix form:\n");

for(i=1; i<=n; i++) {

for(j=1;j<=n;j++) {

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

}
printf("\n Enter the starting vertex:");

scanf("%d", &v);

bfs(v);

printf("\n The node which are reachable are:\n");

for(i=1; i <= n; i++) {

if(visited[i])

printf("%d\t", i);

else {

printf("\n Bfs is not possible. Not all


nodes are reachable");

break;

}
13 b) Deapth first search

#include<stdio.h>

void DFS(int);

int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]

void main()

int i,j;

printf("Enter number of vertices:");

scanf("%d",&n);

//read the adjecency matrix

printf("\nEnter adjecency matrix of the graph:");

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

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

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

//visited is initialized to zero

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

visited[i]=0;

DFS(0);

void DFS(int i)
{

int j;

printf("\n%d",i);

visited[i]=1;

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

if(!visited[j]&&G[i][j]==1)

DFS(j);

}
13 c ) Dijkstra Algorithm

#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

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

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

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

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

return 0;

void dijkstra(int G[MAX][MAX],int n,int startnode)

{
int cost[MAX][MAX],distance[MAX],pred[MAX];

int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far

//create the cost matrix

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

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

if(G[i][j]==0)

cost[i][j]=INFINITY;

else

cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]

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

distance[i]=cost[startnode][i];

pred[i]=startnode;

visited[i]=0;

distance[startnode]=0;

visited[startnode]=1;

count=1;

while(count<n-1)

{
mindistance=INFINITY;

//nextnode gives the node at minimum distance

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

if(distance[i]<mindistance&&!visited[i])

mindistance=distance[i];

nextnode=i;

//check if a better path exists through nextnode

visited[nextnode]=1;

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

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

distance[i]=mindistance+cost[nextnode][i];

pred[i]=nextnode;

count++;

//print the path and distance of each node

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

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);
j=i;

do

j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

}
14 a) Prim’s algorithm

#include<stdio.h>

#include<stdlib.h>

#define infinity 9999

#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;

int prims();

int main()

int i,j,total_cost;

printf("Enter no. of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

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

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

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

total_cost=prims();

printf("\nspanning tree matrix:\n");

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

{
printf("\n");

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

printf("%d\t",spanning[i][j]);

printf("\n\nTotal cost of spanning tree=%d",total_cost);

return 0;

int prims()

int cost[MAX][MAX];

int u,v,min_distance,distance[MAX],from[MAX];

int visited[MAX],no_of_edges,i,min_cost,j;

//create cost[][] matrix,spanning[][]

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

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

if(G[i][j]==0)

cost[i][j]=infinity;

else

cost[i][j]=G[i][j];

spanning[i][j]=0;

//initialise visited[],distance[] and from[]

distance[0]=0;

visited[0]=1;
for(i=1;i<n;i++)

distance[i]=cost[0][i];

from[i]=0;

visited[i]=0;

min_cost=0; //cost of spanning tree

no_of_edges=n-1; //no. of edges to be added

while(no_of_edges>0)

//find the vertex at minimum distance from the tree

min_distance=infinity;

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

if(visited[i]==0&&distance[i]<min_distance)

v=i;

min_distance=distance[i];

u=from[v];

//insert the edge in spanning tree

spanning[u][v]=distance[v];

spanning[v][u]=distance[v];

no_of_edges--;

visited[v]=1;
//updated the distance[] array

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

if(visited[i]==0&&cost[i][v]<distance[i])

distance[i]=cost[i][v];

from[i]=v;

min_cost=min_cost+cost[u][v];

return(min_cost);

Output

Enter no. of vertices:6

Enter the adjacency matrix:


031600
305030
150564
605002
036006
004260

spanning tree matrix:

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

Total cost of spanning tree=13


14 b) Kruskal’s algorithm

#include<stdio.h>

#define MAX 30

typedef struct edge

int u,v,w;

}edge;

typedef struct edgelist

edge data[MAX];

int n;

}edgelist;

edgelist elist;

int G[MAX][MAX],n;

edgelist spanlist;

void kruskal();

int find(int belongs[],int vertexno);

void union1(int belongs[],int c1,int c2);

void sort();

void print();
void main()

int i,j,total_cost;

printf("\nEnter number of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

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

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

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

kruskal();

print();

void kruskal()

int belongs[MAX],i,j,cno1,cno2;

elist.n=0;

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

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

if(G[i][j]!=0)

{
elist.data[elist.n].u=i;

elist.data[elist.n].v=j;

elist.data[elist.n].w=G[i][j];

elist.n++;

sort();

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

belongs[i]=i;

spanlist.n=0;

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

cno1=find(belongs,elist.data[i].u);

cno2=find(belongs,elist.data[i].v);

if(cno1!=cno2)

spanlist.data[spanlist.n]=elist.data[i];

spanlist.n=spanlist.n+1;

union1(belongs,cno1,cno2);

}
int find(int belongs[],int vertexno)

return(belongs[vertexno]);

void union1(int belongs[],int c1,int c2)

int i;

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

if(belongs[i]==c2)

belongs[i]=c1;

void sort()

int i,j;

edge temp;

for(i=1;i<elist.n;i++)

for(j=0;j<elist.n-1;j++)

if(elist.data[j].w>elist.data[j+1].w)

temp=elist.data[j];

elist.data[j]=elist.data[j+1];

elist.data[j+1]=temp;

}
void print()

int i,cost=0;

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

printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);

cost=cost+spanlist.data[i].w;

printf("\n\nCost of the spanning tree=%d",cost);

}
15 Add two Polynomial expressions

/**

* Add two polynomials

* Using Linked List

* @author Swashata

* @for Dearest Froggie

*/

#include<stdio.h>

#include<stdlib.h>

/**

* The structure for the polynomial

* This is a linked list with two variable

* int coeff The Coefficient

* int pow The power of x

*/

typedef struct link {

int coeff;

int pow;

struct link * next;

} my_poly;

/** The prototypes */

void my_create_poly(my_poly **);

void my_show_poly(my_poly *);

void my_add_poly(my_poly **, my_poly *, my_poly *);

/**
* The simple menu driven main function

*/

int main(void) {

int ch;

do {

my_poly * poly1, * poly2, * poly3;

printf("\nCreate 1st expression\n");

my_create_poly(&poly1);

printf("\nStored the 1st expression");

my_show_poly(poly1);

printf("\nCreate 2nd expression\n");

my_create_poly(&poly2);

printf("\nStored the 2nd expression");

my_show_poly(poly2);

my_add_poly(&poly3, poly1, poly2);

my_show_poly(poly3);

printf("\nAdd two more expressions? (Y = 1/N = 0): ");

scanf("%d", &ch);

} while (ch);

return 0;

/**

* The create polynomial function

* @param my_poly ** node The pointer to the head of the polynomial


* We will modify the parameter and will store the base address

* @return void

*/

void my_create_poly(my_poly ** node) {

int flag; //A flag to control the menu

int coeff, pow;

my_poly * tmp_node; //To hold the temporary last address

tmp_node = (my_poly *) malloc(sizeof(my_poly)); //create the first node

*node = tmp_node; //Store the head address to the reference variable

do {

//Get the user data

printf("\nEnter Coeff:");

scanf("%d", &coeff);

tmp_node->coeff = coeff;

printf("\nEnter Pow:");

scanf("%d", &pow);

tmp_node->pow = pow;

//Done storing user data

//Now increase the Linked on user condition

tmp_node->next = NULL;

//Ask user for continuation

printf("\nContinue adding more terms to the polynomial list?(Y = 1/N = 0): ");

scanf("%d", &flag);

//printf("\nFLAG: %c\n", flag);

//Grow the linked list on condition

if(flag) {

tmp_node->next = (my_poly *) malloc(sizeof(my_poly)); //Grow the list


tmp_node = tmp_node->next;

tmp_node->next = NULL;

} while (flag);

/**

* The show polynomial function

* Prints the Polynomial in user readable format

* @param my_poly * node The polynomial linked list

* @return void

*/

void my_show_poly(my_poly * node) {

printf("\nThe polynomial expression is:\n");

while(node != NULL) {

printf("%dx^%d", node->coeff, node->pow);

node = node->next;

if(node != NULL)

printf(" + ");

/**

* The polynomial add function

* Adds two polynomial to a given variable

* @param my_poly ** result Stores the result

* @param my_poly * poly1 The first polynomial expression

* @param my_poly * poly2 The second polynomial expression

* @return void
*/

void my_add_poly(my_poly ** result, my_poly * poly1, my_poly * poly2) {

my_poly * tmp_node; //Temporary storage for the linked list

tmp_node = (my_poly *) malloc(sizeof(my_poly));

tmp_node->next = NULL;

*result = tmp_node; //Copy the head address to the result linked list

//Loop while both of the linked lists have value

while(poly1 && poly2) {

if (poly1->pow > poly2->pow) {

tmp_node->pow = poly1->pow;

tmp_node->coeff = poly1->coeff;

poly1 = poly1->next;

else if (poly1->pow < poly2->pow) {

tmp_node->pow = poly2->pow;

tmp_node->coeff = poly2->coeff;

poly2 = poly2->next;

else {

tmp_node->pow = poly1->pow;

tmp_node->coeff = poly1->coeff + poly2->coeff;

poly1 = poly1->next;

poly2 = poly2->next;

//Grow the linked list on condition

if(poly1 && poly2) {

tmp_node->next = (my_poly *) malloc(sizeof(my_poly));


tmp_node = tmp_node->next;

tmp_node->next = NULL;

//Loop while either of the linked lists has value

while(poly1 || poly2) {

//We have to create the list at beginning

//As the last while loop will not create any unnecessary node

tmp_node->next = (my_poly *) malloc(sizeof(my_poly));

tmp_node = tmp_node->next;

tmp_node->next = NULL;

if(poly1) {

tmp_node->pow = poly1->pow;

tmp_node->coeff = poly1->coeff;

poly1 = poly1->next;

if(poly2) {

tmp_node->pow = poly2->pow;

tmp_node->coeff = poly2->coeff;

poly2 = poly2->next;

printf("\nAddition Complete");

}
Output:

You might also like