Top Banner
A.R ENGINEERING COLLEGE VILLUPURAM Department of Electrical and Electronics Engineering Lab Manual Data Structures and Algorithms Lab (III Semester IT) 1
76
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lab Manual - Ds

A.R ENGINEERING COLLEGEVILLUPURAM

Department of Electrical and Electronics Engineering

Lab Manual

Data Structures and Algorithms Lab

(III Semester IT)

Prepared by:

Ms. C. Saranya

(Lect. / EEE)

1

Page 2: Lab Manual - Ds

DATA STRUCTURES AND ALGORITHMS LABORATORY

Aim:To develop skills in design and implementation of data structures and their applications.

1. Implement singly and doubly linked lists.

2. Represent a polynomial as a linked list and write functions for polynomial addition.

3. Implement stack and use it to convert infix to postfix expression

4. Implement array-based circular queue and use it to simulate a producer consumer problem.

5. Implement an expression tree. Produce its pre-order, in-order, and post-order traversals.

6. Implement binary search tree.

7. Implement insertion in AVL trees.

8. Implement priority queue using heaps

9. Implement hashing techniques

10.Implement Dijkstra's algorithm using priority queues

11. Implement Prim's and Kruskal's algorithms

2

Page 3: Lab Manual - Ds

IMPLEMENTATION OF SINGLY LINKED LIST

AIM:-

To write a ‘C’ program to create a singly linked list implementation.

ALGORITHM:-

1. Start the program.

2. Get the choice from the user.

3. If the choice is to add records, get the data from the user and add them to the list.

4. If the choice is to delete records, get the data to be deleted and delete it from the list.

5. If the choice is to display number of records, count the items in the list and display.

6. Terminate the program

3

Page 4: Lab Manual - Ds

PROGRAM:

#include<stdio.h>#include<conio.h>#include<alloc.h>#define NULL 0struct info{ int data; struct info *next;};struct info *head,*temp,*disp;void additem();void delitem();void display();int size();void main(){int choice;clrscr();while(1){ printf("\n1.Add records");

printf("\n2.Delete records");printf("\n3.Display records");printf("\n4.Exit");printf("\nEnter your choice:");scanf("%d",&choice);fflush(stdin);

switch(choice){case 1: additem(); break;case 2: delitem(); break;case 3: display(); break;case 4: exit(0);}}}void additem(){ struct info *add;

char proceed='y';while(toupper(proceed)=='Y'){

4

Page 5: Lab Manual - Ds

add=(struct info*)malloc(sizeof(struct info));printf("Enter data:");scanf("%d",&add->data);fflush(stdin);if(head==NULL){

head=add;add->next=NULL;temp=add;

}else{ temp->next=add;

add->next=NULL;temp=add;

}printf("\nWant to proceed y/n");proceed=getchar();fflush(stdin);}}void delitem(){ struct info *curr,*prev;

int tdata;if(head==NULL){

printf("\nNo records to delete");return;

}printf("\nEnter the data to delete");scanf("%d",&tdata);fflush(stdin);prev=curr=head;while((curr!=NULL)&&(curr->data!=tdata)){ prev=curr;

curr=curr->next;}if(curr==NULL){

printf("\nData not found");return;

}if(curr==head)

head=head->next;else{/*for inbetween element deletion*/prev->next=curr->next;

5

Page 6: Lab Manual - Ds

/*for the last element deletion*/if(curr->next==NULL)

temp=prev;}free(curr);

}void display(){

if(head==NULL){ printf("\nNo data to display");

return;}for(disp=head;disp!=NULL;disp=disp->next){ printf("Data->%d",disp->data);}

}

6

Page 7: Lab Manual - Ds

OUTPUT:

1.Add records2.Delete records3.Display records4.ExitEnter your choice:1Enter data:23Want to proceed y/nyEnter data:45Want to proceed y/nyEnter data:67Want to proceed y/nn

1.Add records2.Delete records3.Display records4.Exit

Enter your choice:3Data->23Data->45Data->67

1.Add records2.Delete records3.Display records4.ExitEnter your choice:2Enter the data to delete45

1.Add records2.Delete records3.Display records4.ExitEnter your choice:3Data->23Data->671.Add records2.Delete records3.Display records4.ExitEnter your choice:4

RESULT:-

The given program is implemented, executed, tested and verified successfully.

7

Page 8: Lab Manual - Ds

IMPLEMENTATION OF DOUBLY LINKED LIST

AIM:-

To write a ‘C’ program to create a Doubly linked list implementation.

ALGORITHM:-

1. Start the program.

2. Get the choice from the user.

3. If the choice is to add records, get the data from the user and add them to the list.

4. If the choice is to delete records, get the data to be deleted and delete it from the list.

5. If the choice is to display number of records, count the items in the list and display.

6. Terminate the program.

8

Page 9: Lab Manual - Ds

PROGRAM:

#include<stdio.h>#include<conio.h>#include<alloc.h>#define NULL 0struct info{

int data;struct info *next;struct info *prev;

};struct info *head,*temp,*disp;void additem();void delitem();void display();int size();void main(){

int choice;clrscr();while(1){

printf("\n1.Add records");printf("\n2.Delete records");printf("\n3.Display records");printf("\n4.Exit");printf("\nEnter your choice:");scanf("%d",&choice);fflush(stdin);switch(choice){

case 1: additem(); break;case 2: delitem(); break;case 3: display(); break;case 4: exit(0);

}}

}

9

Page 10: Lab Manual - Ds

void additem(){

struct info *add;char proceed='y';while(toupper(proceed)=='Y'){

add=(struct info*)malloc(sizeof(struct info));printf("Enter data:");scanf("%d",&add->data);fflush(stdin);if(head==NULL){head=add;add->next=NULL;add->prev=NULL;temp=add;}else{temp->next=add;add->prev=temp;add->next=NULL;temp=add;}printf("\nWant to proceed y/n");proceed=getchar();fflush(stdin);

}}void delitem(){

int x;struct info *p;;if(head==NULL){

printf("\nNo items in the list");return;

}printf("\nEnter the data to delete");scanf("%d",&x);p=(struct info *)malloc(sizeof(struct info));p=head->next;if(head->data==x){ head=head->next;

return;}

10

Page 11: Lab Manual - Ds

while(p){

if(p->data==x){p->prev->next=p->next;if(p->next!=NULL) p->next->prev=p->prev;else temp=p->prev;return;}else{ p=p->next;}

}printf("\nInvalid input");

}void display(){ if(head==NULL)

{printf("\nNo data to display");return;}printf("\nFrom forward direction\n");for(disp=head;disp!=NULL;disp=disp->next){printf("Data->%d",disp->data);}printf("\nFrom backward direction\n");for(disp=temp;disp!=NULL;disp=disp->prev){ printf("Data->%d",disp->data);}

}

11

Page 12: Lab Manual - Ds

OUTPUT1. Add records2.Delete records3.Display records4.ExitEnter your choice:1Enter data:23Want to proceed y/nyEnter data:78Want to proceed y/nyEnter data:12Want to proceed y/nyEnter data:34Want to proceed y/nn1.Add records2.Delete records3.Display records4.ExitEnter your choice:3From forward directionData->23Data->78Data->12Data->34From backward directionData->34Data->12Data->78Data->231.Add records2.Delete records3.Display records4.ExitEnter your choice:2Enter the data to delete781.Add records2.Delete records3.Display records4.ExitEnter your choice:3From forward directionData->23Data->12Data->34From backward directionData->34Data->12Data->231.Add records2.Delete records3.Display records4.ExitEnter your choice:4

RESULT:The given program is implemented, executed, tested and verified successfully.

12

Page 13: Lab Manual - Ds

POLYNOMIAL ADDTION USING LINKED LIST

AIM:-

To write a ‘C’ program to represent a polynomial as a linked list and write functions for

polynomial addition

ALGORITHM:-

1. Start the program

2. Get the coefficients and powers for the two polynomials to be added.

3. Add the coefficients of the respective powers.

4. Display the added polynomial.

5. Terminate the program.

13

Page 14: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>struct polynomial{ int coff;

int pow;struct polynomial *link;

}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;typedef struct polynomial pnl;int temp1,temp2;void main(){ void create(void);

void prnt(void);void suml(void);clrscr();printf("\n\nEnter the elements of the first polynomial :");node = (pnl *) malloc(sizeof (pnl));start1=node;if (start1==NULL){ printf(" Unable to create memory.");

getch();exit();

}create();printf("Enter the elements of the second poly :");node = (pnl *) malloc(sizeof (pnl));start2=node;if (start2==NULL){ printf("Unable to create memory.");

getch();exit();

} create();printf("\n\nThe elements of the poly first are :");ptr=start1;prnt();printf("\n\nThe elements of the poly second are :");ptr=start2;prnt();printf("\n\nThe sum of the two lists are :");suml();ptr=start3;prnt();getch();

}void create(){ char ch;

14

Page 15: Lab Manual - Ds

while(1){

printf(" Enter the coff and pow :");scanf("%d%d",&node->coff,&node->pow);if (node->pow==0 ){ptr=node;node=(pnl *)malloc(sizeof(pnl));node=NULL;ptr->link=node;break;}printf("Do u want enter more coff ?(y/n)");fflush(stdin);scanf("%c",&ch);if (ch=='n' ){ptr=node;node=(pnl *)malloc(sizeof(pnl));node=NULL;ptr->link=node;break;}ptr=node;node=(pnl *)malloc(sizeof(pnl));ptr->link=node;

}}void prnt(){ int i=1;

while(ptr!=NULL ){ if(i!=1)

printf("+ ");printf(" %dx^%d\t ",ptr->coff,ptr->pow);ptr=ptr->link;i++;

}}void suml(){ node=(pnl *)malloc (sizeof(pnl));

start3=node;ptr1=start1;ptr2=start2;while(ptr1!=NULL && ptr2!=NULL){ ptr=node;

if (ptr1->pow > ptr2->pow )

15

Page 16: Lab Manual - Ds

{ node->coff=ptr2->coff;node->pow=ptr2->pow;ptr2=ptr2->link; //update ptr list B

}else if ( ptr1->pow < ptr2->pow ){ node->coff=ptr1->coff;

node->pow=ptr1->pow;ptr1=ptr1->link; //update ptr list A

}else{ node->coff=ptr2->coff+ptr1->coff;

node->pow=ptr2->pow;ptr1=ptr1->link; //update ptr list Aptr2=ptr2->link; //update ptr list B

}node=(pnl *)malloc (sizeof(pnl));ptr->link=node; //update ptr list C

}//end of whileif (ptr1==NULL) //end of list A{

while(ptr2!=NULL){ node->coff=ptr2->coff;

node->pow=ptr2->pow;ptr2=ptr2->link; //update ptr list Bptr=node;node=(pnl *)malloc (sizeof(pnl));ptr->link=node; //update ptr list C

}}else if (ptr2==NULL) //end of list B{

while(ptr1!=NULL){ node->coff=ptr1->coff;

node->pow=ptr1->pow;ptr1=ptr1->link; //update ptr list Bptr=node;node=(pnl *)malloc (sizeof(pnl));ptr->link=node; //update ptr list C

}}node=NULL;ptr->link=node;}

16

Page 17: Lab Manual - Ds

OUTPUT:

Enter the elements of the first polynomial : Enter the coff and pow :11Do u want enter more coff ?(y/n)y Enter the coff and pow :22Do u want enter more coff ?(y/n)nEnter the elements of the second poly : Enter the coff and pow :22Do u want enter more coff ?(y/n)nThe elements of the poly first are : 1x^1 + 2x^2The elements of the poly second are : 2x^2The sum of the two lists are : 1x^1 + 4x^2

RESULT:

The given program is implemented, executed, tested and verified successfully.

17

Page 18: Lab Manual - Ds

ARRAY IMPLEMENTATION OF STACK

AIMTo write a C program to implement array based stack.

ALGORITHM

1. Start the program.

2. To insert an element,

Step-i: Insert the element into the stack using push() function

Step-ii: Insert the new value to the stack until stack overflow

3. To delete the particular item from circular queue

Step-i: Delete the element from the stack using pop() function

Stepii: Delete the “last” element

Stepiii: Delete until stack value is zero

4. Terminate the program.

18

Page 19: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>struct node{/*variable to get the element*/int data;/*variable to hold the list of element*/struct node *next;}*top=NULL,*p;void main(){int c;/*function declaration to insert element into stack*/void push();/*function declaration to delete element from the stack*/void pop();/*function declaration to display element in the stack*/void display();clrscr();printf("\n1.Push \t 2.Pop \t 3.Display \t 4.Exit\n");while(1) {

printf("\n Enter the choice to perform stack operation");scanf("%d",&c);switch(c){case 1: push(); break;case 2: pop(); break;case 3: display(); break;case 4: exit(0);}

}}

19

Page 20: Lab Manual - Ds

void push(){ p=(struct node*)malloc(sizeof(struct node));

printf("\n Enter data to be inserted:\n");scanf("%d",&p->data);p->next=top;/*assign the top value to next position*/top=p;

}void pop(){

if(top==NULL){ printf("\nStack Empty");}else{

p=top;top=top->next;free(p);

}}void display(){

if(top==NULL){

printf("\n Stack Empty");}else{

p=top;while(p->next!=NULL){

printf("%d\n",p->data);p=p->next;

}printf("%d",p->data);

}}

20

Page 21: Lab Manual - Ds

OUTPUT

1.Push 2.Pop 3.Display 4.Exit

Enter the choice to perform stack operation1 Enter data to be inserted:45 Enter the choice to perform stack operation1 Enter data to be inserted:69 Enter the choice to perform stack operation1 Enter data to be inserted:57 Enter the choice to perform stack operation3576945 Enter the choice to perform stack operation2 Enter the choice to perform stack operation2 Enter the choice to perform stack operation2 Enter the choice to perform stack operation2 Stack Empty Enter the choice to perform stack operation4

RESULT:

The given program is implemented, executed, tested and verified successfully.

21

Page 22: Lab Manual - Ds

CONVERSION OF INFIX TO POSTFIX EXPRESSION USING STACK

AIM

To write a ‘C’ program to implement stack and use it to convert infix to postfix

expression.

ALGORITHM:-

1. Start the program

2. Scan the Infix string from left to right.

3. Initialize an empty stack.

4. If the scanned character is an operand, add it to the Postfix string. If the scanned

character is an operator and if the stack is empty Push the character to stack.

If the scanned character is an Operand and the stack is not empty, compare the

precedence of the character with the element on top of the stack (top Stack). If

top Stack has higher precedence over the scanned character Pop the stack else

Push the scanned character to stack. Repeat this step as long as stack is not

empty and top Stack has precedence over the character.

Repeat this step till all the characters are scanned.

5. (After all characters are scanned, we have to add any character that the stack may

have to the Postfix string.) If stack is not empty add top Stack to Postfix string and

Pop the stack. Repeat this step as long as stack is not empty.

6. Return the Postfix string.

7. Terminate the program.

22

Page 23: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>char inf[40],post[40];int top=0,st[20];void postfix();void push(int);char pop();void main(){clrscr();printf("\n\t Enter the infix expression:\t");scanf("%s",inf);postfix();getch();}void postfix()

{ int i,j=0; for(i=0;inf[i]!='\0';i++) {

switch(inf[i]){case '+':

while(st[top]>=1)post[j++]=pop();push(1);break;

case '-':while(st[top]>=1)post[j++]=pop();push(2);break;

case '*':while(st[top]>=3)post[j++]=pop();push(3);break;

case '/':while(st[top]>=3)post[j++]=pop();push(4);break;

case '(':push(0);break;

23

Page 24: Lab Manual - Ds

case ')':while(st[top]!=0)post[j++]=pop();top--;break;

default:post[j++]=inf[i];

}}

while(top>0)post[j++]=pop();printf("\n Postfix expression is : \t%s", post);

}void push(int ele){top++;st[top]=ele;}char pop(){int el;char e;el=st[top];top--;switch(el){

case 1:e='+';break;

case 2:e='-';break;

case 3:e='*';break;

case 4: e='/'; break;

}return(e);}

24

Page 25: Lab Manual - Ds

OUTPUT:

Enter the infix expression: A+B-(C/D) Postfix expression is: AB+CD/-

RESULT:

The given program is implemented, executed, tested and verified successfully.

25

Page 26: Lab Manual - Ds

ARRAY IMPLEMENTATION OF CIRCULAR QUEUE

AIMTo write a ‘C’ program to implement array based circular queue and use it to simulate a

producer-consumer problem

ALGORITHM:-

1. Start the program

2. To insert an element,

Step-i: If "rear" of the queue is pointing to the last position then go to step-ii or else

step-iii

Step-ii: make the "rear" value as 0

Step-iii: increment the "rear" value by one

Step-iv: a. if the "front" points where "rear" is pointing and the queue holds a

not NULL value for it, then its a "queue overflow" state, so quit; else go to

step-b

  b. insert the new value for the queue position pointed by the "rear"

3. To delete the particular item from circular queue

Step-i: If the queue is empty then say "empty queue" and quit; else continue

Step-ii: Delete the "front" element

Step-iii: If the "front" is pointing to the last position of the queue then step-iv else

step-v

Step-iv: Make the "front" point to the first position in the queue and quit

Step-v: Increment the "front" position by one 

4. Terminate the program.

26

Page 27: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>#define size 4int queue[size];int front=-1;int rear=0;void add(int item){if(front==(rear+1)%size)printf("\n queue overflow");else{

if(front==-1) front=rear=0;else rear=(rear+1)%size; queue[rear]=item;

}}void delete(){int item;if(front==-1) printf("\n Queue underflow");else {

item=queue[front];if(front==rear){

front=rear=-1;}elsefront=(front+1)%size;printf("\n The deleted item is %d\t",item);

}}void display(){int i;if(front==-1){printf("\n Queue underflow");}else

27

Page 28: Lab Manual - Ds

{printf("\n Element in queue:\n");i=front;while(i!=rear)

{printf("%d\t",queue[i]);i=(i+1)%size;

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

}}void main(){int choice,item;char ans;clrscr();printf("\n Main Menu");printf("\n\n1.Insert \t 2.Delete\t 3.Display\t 4.Exit\n");do{printf("\n Enter your choice:");scanf("%d",&choice);switch(choice){

case 1:printf("\n\n Enter the element:");scanf("%d",&item);add(item);break;

case 2:delete();break;

case 3:display();break;

case 4:exit(0);

}}while(choice<4);getch();}

28

Page 29: Lab Manual - Ds

OUTPUT

Main Menu

1. Insert 2.Delete 3.Display 4.Exit

Enter your choice:1 Enter the element:23

Enter your choice:1 Enter the element:45 Enter your choice:1Enter the element:67

Enter your choice:1 Enter the element:90 queue overflow

Enter your choice:3 Element in queue:23 45 67 Enter your choice:2 The deleted item is 23 Enter your choice:2The deleted item is 45

Enter your choice:2The deleted item is 67 Enter your choice:2Queue underflow

Enter your choice:4

RESULT:

The given program is implemented, executed, tested and verified successfully.

IMPLEMENTATION OF EXPRESSION TREE

29

Page 30: Lab Manual - Ds

AIM:-

To write a ‘C’ program to implement an expression tree. Produce its pre-order, in-order, and post-order traversals.

ALGORITHM:-

Step 1: Start the process.

Step 2: Initialize and declare variables.

Step 3: Enter the choice. Inorder / Preorder / Postorder.

Step 4: If choice is Inorder then

Traverse the left subtree in inorder.

Process the root node.

Traverse the right subtree in inorder.

Step 5: If choice is Preorder then

Process the root node.

Traverse the left subtree in preorder.

Traverse the right subtree in preorder.

Step 6: If choice is postorder then

Traverse the left subtree in postorder.

Traverse the right subtree in postorder.

Process the root node.

Step7: Print the Inorder / Preorder / Postorder traversal.

Step 8: Stop the process.

PROGRAM

30

Page 31: Lab Manual - Ds

#include<stdio.h>#include<conio.h>#include<alloc.h>#include<ctype.h>#define size 30typedef struct node{ char data;

struct node*left;struct node*right;

} btree;btree *stack[size];int top;

void main(){ btree *root;

char exp[80];btree *create(char exp[80]);void displayin(btree *root);void displaypre(btree *root);void displaypost(btree *root);clrscr();printf("Enter the postfix expression:\n");scanf("%s",exp);top=-1;root=create(exp);printf("\n The tree is created");printf("\n The inorder traversal is;");displayin(root);printf("\n The preorder traversal is:");displaypre(root);printf("\n The postorder traversal is:");displaypost(root);getch();

}btree* create(char exp[]){ btree *temp;

int pos;char ch;void push(btree *);btree *pop();pos=0;ch=exp[pos];while(ch!='\0'){ temp=(btree *)malloc(sizeof(btree));

temp->left=temp->right=NULL;temp->data=ch;if(isalpha(ch))

31

Page 32: Lab Manual - Ds

push(temp);else if(ch=='+'||ch=='-'||ch=='/'){ temp->right=pop();

temp->left=pop();push(temp);

}elseprintf("invalid character in expression \n");pos++;ch=exp[pos];

}temp=pop();return(temp);

}void push(btree *node){ if(top+1>=size)

printf("Error stack is full\n");top++;stack[top]=node;

}btree* pop(){ btree *node;

if(top==1)printf("\nError stack is empty");node=stack[top];top--;return(node);

}void displayin(btree *root){ btree *temp;

temp=root;if(temp!=NULL){ displayin(temp->left);

printf("%c",temp->data);displayin(temp->right);

}}void displaypre(btree *root){ btree *temp;

temp=root;if(temp!=NULL){ printf("%c",temp->data);

displaypre(temp->left);displaypre(temp->right);

}}void displaypost(btree *root)

32

Page 33: Lab Manual - Ds

{btree *temp;temp=root;if(temp!=NULL){

displaypost(temp->left);displaypost(temp->right);printf("%c",temp->data);

}}

33

Page 34: Lab Manual - Ds

OUTPUT

Enter the postfix expression:ab+Error stack is empty The tree is created The inorder traversal is;a+b The preorder traversal is:+ab The postorder traversal is:ab+

RESULT:

The given program is implemented, executed, tested and verified successfully.

34

Page 35: Lab Manual - Ds

IMPLEMENTATION OF BINARY SEARCH TREE

AIM:-

To write a ‘C’ program to implement binary search tree.

ALGORITHM:-

Step 1: Start the process.

Step 2: Initialize and declare variables.

Step 3: Construct the Tree

Step 4: Data values are given which we call a key and a binary search tree

Step 5: To search for the key in the given binary search tree, start with the root node and Compare the key with the data value of the root node. If they match, return the root pointer.

Step 6: If the key is less than the data value of the root node, repeat the process by using the left subtree.

Step 7: Otherwise, repeat the same process with the right subtree until either a match is found or the subtree under consideration becomes an empty tree.

Step 8: Terminate

35

Page 36: Lab Manual - Ds

PROGRAM #include<stdio.h>#include<conio.h>#include<stdlib.h>typedef struct tree *node;node insert(int, node T);node FindMin(node T);node del(int,node T);void display(node T);void Find(node T,int);struct tree{

int data;struct tree *right,*left;

}*root;void main(){

node T=NULL;int data,n,i=0,s;char c;clrscr();printf("\n Enter the number of element in the tree:");scanf("%d",&n);printf("\n\nEnter the element:");while(i<n){

scanf("%d",&data);T=insert(data,T);i++;

}printf("\nElement displayed in order format:\n");display(T);printf("\nEnter the element to delete:\n");scanf("%d",&data);T=del(data,T);printf("\nContent of tree after deletion:\n");display(T);printf("\nEnter the element to search:\n");scanf("%d",&s);Find(T,s);getch();

}node insert(int X,node T){struct tree *newnode;

36

Page 37: Lab Manual - Ds

newnode=malloc(sizeof(struct tree));if(newnode==NULL)

printf("\nOut of space\n");else

{if(T==NULL) {

newnode->data=X;newnode->left=NULL;newnode->right=NULL;T=newnode;

}else {

if(X<T->data) T->left=insert(X,T->left);else T->right=insert(X,T->right);

}}return T;

}node del(int X,node T){node TmpCell;if(T==NULL)

printf("\nElement not found");elseif(X<T->data)

T->left=del(X,T->left);elseif(X>T->data)

T->right=del(X,T->right);elseif(T->left&&T->right)

{TmpCell=FindMin(T->right);T->data=TmpCell->data;T->right=del(T->data,T->right);

}else{

TmpCell=T;if(T->left==NULL)T=T->right;else if(T->right==NULL)

37

Page 38: Lab Manual - Ds

T=T->left;free(TmpCell);

} return T;}node FindMin(node T){if(T!=NULL)

{if(T->left==NULL) return T;else return FindMin(T->left);

}return 0;}void display(node T){

if(T!=NULL){

display(T->left);printf("%d\t",T->data);display(T->right);

}}void Find(node T,int X){if(T==NULL)

printf("\nSearch element not found");else{

if(T->data==X) printf("\n Search Element found");else if(X<T->data) Find(T->left,X);else Find(T->right,X);

}}

38

Page 39: Lab Manual - Ds

OUTPUT

Enter the number of element in the tree:3 Enter the element:12 25 23 Element displayed in order format: 12 23 25 Enter the element to delete:12 Content of tree after deletion: 23 25 Enter the element to search: 23 Search Element found

RESULT

The given program is implemented, executed, tested and verified successfully.

39

Page 40: Lab Manual - Ds

IMPLEMENTATION OF INSERTION IN AVL TREE

AIMTo write a ‘C’ program to implement an AVL tree.

ALGORITHM

1. Start the program.

2. Declare the structure of binary search tree.

3. Insert element into the tree.

4. To insert another element into the tree check the balance factor of each node,

according to that make a rotation.

5. Display the resultant height of balanced tree.

6. Stop the program.

40

Page 41: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>typedef int ElementType;struct AvlNode;typedef struct AvlNode *Position;typedef struct AvlNode *AvlTree;AvlTree MakeEmpty( AvlTree T );AvlTree Insert( ElementType X, AvlTree T );void display(AvlTree T);struct AvlNode{ ElementType Element;

AvlTree Left;AvlTree Right;int Height;

};void display(AvlTree T){ if(T->Left!=NULL)

display(T->Left);if(T->Right!=NULL)

display(T->Right);printf("\t%d",T->Element);

}AvlTree MakeEmpty( AvlTree T ){ if( T != NULL )

{ MakeEmpty( T->Left );MakeEmpty( T->Right );free( T );

}return NULL;

}static int Height( Position P ){ if( P == NULL )

return -1;else

return P->Height;}static int Max( int Lhs, int Rhs ){ return Lhs > Rhs ? Lhs : Rhs;}static Position SingleRotateWithLeft( Position K2 ){ Position K1;

K1 = K2->Left;K2->Left = K1->Right;K1->Right = K2;

41

Page 42: Lab Manual - Ds

K2->Height = Max( Height( K2->Left ), Height( K2->Right ) ) + 1;K1->Height = Max( Height( K1->Left ), K2->Height ) + 1;return K1; /* New root */

}static Position SingleRotateWithRight( Position K1 ){ Position K2;

K2 = K1->Right;K1->Right = K2->Left;K2->Left = K1;K1->Height = Max( Height( K1->Left ), Height( K1->Right ) ) + 1;K2->Height = Max( Height( K2->Right ), K1->Height ) + 1;return K2; /* New root */

}static Position DoubleRotateWithLeft( Position K3 ){ K3->Left = SingleRotateWithRight( K3->Left );

return SingleRotateWithLeft( K3 );}static Position DoubleRotateWithRight( Position K1 ){ K1->Right = SingleRotateWithLeft( K1->Right );

return SingleRotateWithRight( K1 );}AvlTree Insert( ElementType X, AvlTree T ){

if( T == NULL ){ T =(AvlTree) malloc( sizeof( struct AvlNode ) );

if( T == NULL )printf( "Out of space!!!" );

else{ T->Element = X; T->Height = 0;

T->Left = T->Right = NULL;}

}else if( X < T->Element ){ T->Left = Insert( X, T->Left );

if( Height( T->Left ) - Height( T->Right ) == 2 )if( X < T->Left->Element )

T = SingleRotateWithLeft( T );else

T = DoubleRotateWithLeft( T );}else if( X > T->Element ){ T->Right = Insert( X, T->Right );

if( Height( T->Right ) - Height( T->Left ) == 2 )if( X > T->Right->Element )

T = SingleRotateWithRight( T );else

42

Page 43: Lab Manual - Ds

T = DoubleRotateWithRight( T );}T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1;return T;

}void main(){

AvlTree T;Position P;int a,ch;T = MakeEmpty( NULL );clrscr();printf("\n1.Insert \t 2.Display \t 3.Exit");while(1){

printf("\nEnter your choice");scanf("%d",&ch);switch(ch){

case 1:printf("enter the element");scanf("%d",&a);T = Insert( a, T );break;case 2:printf("display by postorder traversal\n\t");display(T);break;case 3:exit(0);break;

} }

}

43

Page 44: Lab Manual - Ds

OUTPUT

1.Insert 2.Display 3.ExitEnter your choice 1enter the element 85

Enter your choice 1enter the element 46

Enter your choice 1enter the element 75

Enter your choice 2display by postorder traversal 46 85 75Enter your choice 1enter the element 25

Enter your choice 2display by postorder traversal 25 46 85 75Enter your choice 3

RESULT

The given program is implemented, executed, tested and verified successfully

44

Page 45: Lab Manual - Ds

IMPLEMENTATION OF HASHING TECHNIQUE

AIMTo write a ‘C’ program to implement Hashing Technique using open addressing.

ALGORITHM

1. Start the program.

2. Get the size of hash table.

3. Get the value of index for hash table as -1.

4. Insert the element into hash table and find the index value using linear probing

method.

5. Insert the element into hash table until the size of hash table exceeds.

6. Stop the program.

45

Page 46: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>#include<stdlib.h>#define MAX 10void main(){

int a[MAX],num,key,i;char ans;int create(int);void linear_prob(int[],int,int),display(int[]);clrscr();printf("\n Collision handling by linear probing");for(i=0;i<MAX;i++)a[i]=-1;do{

printf("\n Enter the Number");scanf("%d",&num);key=create(num);linear_prob(a,key,num);printf("\nDo U wish to continue(Y/N)");ans=getch();

}while(ans=='y');display(a);getch();

}int create(int num){

int key;key =num%10;return key;

}void linear_prob(int a[MAX],int key, int num){

int flag,i,count=0;void display(int a[]);flag=0;if(a[key]==-1)a[key]=num;else{

i=0;while(i<MAX){

46

Page 47: Lab Manual - Ds

if(a[i]!=-1){count++;i++;}if(count==MAX){printf("\nHASH TABLE IS FULL");display(a);getch();exit(1);}

for(i=key+1;i<MAX;i++) {

if(a[i]==-1){

a[i]=num;flag=1;break;

} }for(i=0;i<key&&flag==0;i++) {

if(a[i]==-1){

a[i]=num;flag=1;break;

} }

}}}void display(int a[MAX]){int i;printf("\nThe hash table is.......\n");for(i=0;i<MAX;i++)printf("\n%d%d",i,a[i]);getch();}

47

Page 48: Lab Manual - Ds

OUTPUT

Collision handling by linear probing Enter the Number 23

Do U wish to continue(Y/N) Y Enter the Number 45

Do U wish to continue(Y/N) Y Enter the Number 56

Do U wish to continue(Y/N) Y Enter the Number 70

Do U wish to continue(Y/N) NThe hash table is.......

0701-12-13234-15456567-18-19-1

RESULT:

The given program is implemented, executed, tested and verified successfully.

48

Page 49: Lab Manual - Ds

KRUSKAL’S ALGORITHM

AIM

To write a ‘C’ program to find minimum cost spanning tree using Kruskal’s algorithm.

ALGORITHM

1. Start the program.

2. Get the vertices number of graph.

3. Read the graph from an input file.

4. Create a minimum spanning tree, which contains no edges.

5. Choose an edge in the given graph, as follows

Step i: The edge should not be in the tree.

Step ii: The edge should be in minimum weight.

Step iii: There should not be any cycle in the tree.

6. Repeat step4 until the tree traverse all the vertices in the graph.

7. Stop the program.

49

Page 50: Lab Manual - Ds

PROGRAM

#include<stdio.h>#include<conio.h>#define MAX 10#define infinity 9999struct node{

int predecessor;int dist;int status;

};struct edge{

int u;int v;

};int adj[MAX][MAX];int n;void main(){

int i,j;int path[MAX];int mincost,count;struct edge tree[MAX];clrscr();create_graph();count=maketree(tree,&mincost) ;printf("\nedge to be included in spanning tree\n");for(i=1;i<=count;i++){printf("%d->",tree[i].u);printf("%d\n",tree[i].v);}printf("\nWeight of spanning tree is :%d\n",mincost);getch();

}create_graph(){

int i,max_edges,source,destin,wt;printf("Enter no of vertices:");scanf("%d",&n);max_edges=n*(n-1)/2;for(i=1;i<max_edges;i++){

printf("Enter edge %d( 00 to quit):",i);scanf("%d%d",&source,&destin);

50

Page 51: Lab Manual - Ds

if((source==0)&&(destin==0))break;

printf("\nEnter weight of this edges:");scanf("%d",&wt);if(source>n||destin>n||source<=0||destin<=0){ printf("\nInvalid edges");

i--;}else{ adj[source][destin]=wt;

adj[destin][source]=wt;}

}if(i<=n-1){ printf("\nSpanning tree is not possible");

exit(1);}

return;}int maketree(struct edge tree[MAX],int *weight){

struct node state[MAX];int i,k,min,count,current,newdist;int m;int u1,v1;*weight= 0;for(i=1;i<=n;i++){

state[i].predecessor=0;state[i].dist=infinity;state[i].status=0;

}state[1].predecessor=0;state[1].dist=0;state[1].status=1;current=1;count=0;while(all_perm(state)!=1){ for(i=1;i<=n;i++)

{ if(adj[current][i]>0&&state[i].status==0){ if(adj[current][i]<state[i].dist)

{ state[i].predecessor=current; state[i].dist=adj[current][i];}

}}

51

Page 52: Lab Manual - Ds

min= infinity;for(i=1;i<=n;i++){ if(state[i].status==0&&state[i].dist<min)

{ min=state[i].dist;current=i;

}}state[current].status=1;u1=state[current].predecessor;v1=current;count++;

tree[count].u=u1;tree[count].v=v1;*weight=*weight+adj[u1][v1];}

return(count);}int all_perm(struct node state[MAX]){

int i;for(i=1;i<=n;i++) if(state[i].status==0)

return 0;return 1;

}

52

Page 53: Lab Manual - Ds

OUTPUT

Enter no of vertices:4Enter edge 1( 00 to quit): 1 2

Enter weight of this edges:3Enter edge 2( 00 to quit): 1 3

Enter weight of this edges:4Enter edge 3( 00 to quit): 1 4

Enter weight of this edges:1Enter edge 4( 00 to quit): 2 4

Enter weight of this edges:3Enter edge 5( 00 to quit): 3 4

Enter weight of this edges: 2

edge to be included in spanning tree1->44->31->2

Weight of spanning tree is : 6

RESULT:

The given program is implemented, executed, tested and verified successfully.

53

Page 54: Lab Manual - Ds

IMPLEMENTATION OF PRIORITY QUEUE

AIMTo write a ‘C’ program to implement a priority queue

ALGORITHM

1. Start the program.

2. Get the element value, create a queue and insert the value in the queue.

3. Delete the element from the queue.

4. Element with lowest priority is deleted first.

5. If the priority of two element is same then the element is deleted using lowest order

value.

6. Display the element from the queue using display function.

7. Stop the program.

54

Page 55: Lab Manual - Ds

PROGRAM#include<stdio.h>#include<conio.h>#define MAX 5struct data{ int val,p,o; };struct data d[MAX],d2;int front=-1,rear=-1;void insert(struct data d1){ struct data temp;

int i,j;if(rear==MAX-1)

printf("\nPriority queue is full");else{ rear++;

d[rear]=d1;if(front==-1)

front=0;for(i=front;i<=rear;i++)for(j=i+1;j<=rear;j++){ if(d[i].p>d[j].p)

{ temp=d[i]; d[i]=d[j]; d[j]=temp;}else{ if(d[i].p==d[j].p)

{ if(d[i].o>d[j].o){ temp=d[i]; d[i]=d[j]; d[j]=temp;}

}}

}}

}void deletion(){ struct data d1;

if(front==-1) printf("\n Priority queue is empty\n");

else { d1=d[front];

if(front==rear) front=rear=-1;

else front++;

printf("\nDeleted element details are:\n");printf("\tValue\tPriority\tOrder\n");printf("\n\t%d\t%d\t\t%d\t",d1.val,d1.p,d1.o);

}

55

Page 56: Lab Manual - Ds

}void display(){ int i;

if(front==-1) printf("\n Priority queue is empty");else{ printf("\n Element in the priority queue:\n");

printf("\tValue\tPriority\tOrder\n");for(i=front;i<=rear;i++){ printf("\n\t%d\t%d\t\t%d",d[i].val,d[i].p,d[i].o); }

}}void main(){ int op;

int ch;clrscr();printf("1.Insertation\t2.Deletion\t3.Display\t4.Exit");do{ printf("\nEnter your choice:");

scanf("%d",&ch);switch(ch){case 1:

do{ printf("Enter the value:");

scanf("%d",&d2.val);printf("Enter Priority:");scanf("%d",&d2.p);printf("Enter the order:");scanf("%d",&d2.o);insert(d2);printf("\nEnter 1 to insert more or 0 to continue");scanf("%d",&op);

} while(op==1); break;

case 2:deletion();break;

case 3:display();break;

} } while(ch<4);}

56

Page 57: Lab Manual - Ds

OUTPUT

1. Insertion 2.Deletion 3.Display 4.ExitEnter your choice: 1Enter the value: 26Enter Priority: 2Enter the order: 0

Enter 1 to insert more or 0 to continue 1Enter the value: 89Enter Priority: 1Enter the order: 1

Enter 1 to insert more or 0 to continue 0Enter your choice: 3Element in the priority queue: Value Priority Order 89 1 1 26 2 0Enter your choice: 2Deleted element details are: Value Priority Order 89 1 1Enter your choice: 3Element in the priority queue: Value Priority Order 26 2 0Enter your choice: 2Deleted element details are: Value Priority Order 26 2 0Enter your choice: 2Priority queue is empty

Enter your choice: 3Priority queue is emptyEnter your choice: 4

RESULT:

The given program is implemented, executed, tested and verified successfully.

57

Page 58: Lab Manual - Ds

PRIM’S ALGORITHM

AIM

To write a ‘C’ program to find minimum spanning tree using Prim’s algorithm.

ALGORITHM

1. Start the program.

2. Read the number of vertices.

3. Get the cost value for all edges in the graph.

4. Traverse the path in the graph using the lowest cost edges from the first vertex to the

last vertex.

5. Display the minimum cost spanning tree and total minimum cost.

6. Stop the program.

58

Page 59: Lab Manual - Ds

PROGRAM

#include<stdio.h>#define INF 1000int vertex[10];int wght[10][10];int new_wght[10][10];int closed[10];int n;int inclose(int i,int n1){

/*chk for the ith vertex presence in closed*/int j;for(j=0;j<=n1;j++)if(closed[j]==i)return 1;return 0;

}void buildtree(){

int i=0,j,count=0;int min,k,v1=0,v2=0;closed[0]=0;while(count<n-1){

min=INF;for(i=0;i<=count;i++)for(j=0;j<n;j++)if(wght[closed[i]][j]<min && !inclose(j,count)){

min=wght[closed[i]][j];v1=closed[i];v2=j;

}new_wght[v1][v2]=new_wght[v2][v1]=min;count++;closed[count]=v2;printf("\nScan : %d %d---------%d wght = %d \n",count,v1+1,v2+1,min);getch();

}}void main(){

int i,j,ed,sum=0;clrscr();printf("\n\n\tPRIM'S ALGORITHM TO FIND SPANNING TREE\n\n");

59

Page 60: Lab Manual - Ds

printf("\n\tEnter the No. of Nodes : ");scanf("%d",&n);for(i=0;i<n;i++){

vertex[i]=i+1;for(j=0;j<n;j++){

wght[i][j]=INF;new_wght[i][j]=INF;

}}printf("\n\nGetting Weight.\n");printf("\n\tEnter 0 if path doesn't exist between {v1,v2} else enter the wght\n");for(i=0;i<n;i++)for(j=i+1;j<n;j++){

printf("\n\t%d -------- %d : ",vertex[i],vertex[j]);scanf("%d",&ed);if(ed>=1)wght[i][j]=wght[j][i]=ed;

}getch();clrscr();printf("\n\n\t\tNODES CURRENTLY ADDED TO SPANNING TREE\n\n");buildtree();printf("\n\tNEW GRAPH WEIGHT MATRIX\n\n");printf("\n\tweight matrix\n\n\t");for(i=0;i<n;i++,printf("\n\t"))for(j=0;j<n;j++,printf("\t"))printf("%d",new_wght[i][j]);printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");printf("\n\t\tLIST OF EDGES\n\n");for(i=0;i<n;i++)for(j=i+1;j<n;j++)if(new_wght[i][j]!=INF){

printf("\n\t\t%d ------ %d = %d ",vertex[i],vertex[j],new_wght[i][j]);sum+=new_wght[i][j];

}printf("\n\n\t Total Weight : %d ",sum);getch();

}

60

Page 61: Lab Manual - Ds

OUTPUT

PRIM'S ALGORITHM TO FIND SPANNING TREE

Enter the No. of Nodes: 4

Getting Weight.

Enter 0 if path doesn't exist between {v1,v2} else enter the wght

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

NODES CURRENTLY ADDED TO SPANNING TREEScan : 1 1---------2 wght = 2Scan : 2 2---------3 wght = 1Scan : 3 2---------4 wght = 3

NEW GRAPH WEIGHT MATRIX

weight matrix

1000 2 1000 1000 2 1000 1 3 1000 1 1000 1000 1000 3 1000 1000

MINIMUM SPANNING TREELIST OF EDGES 1 ------ 2 = 2

2 ------ 3 = 1 2 ------ 4 = 3

Total Weight : 6

RESULT:

The given program is implemented, executed, tested and verified successfully.

61