Cse-Ds Lab Manual (Cs2208) - 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

Department of Computer Science and Engineering

Subject Code: CS2208 Subject Name: DATA STRUCTURES LAB

Semester : III year : II

List of Questions

1. Write a C program for implementing singly linked list. 2. Write a C program for implementing doubly linked list. 3. Write a C program to represent a polynomial as a linked list and write functions for polynomial addition. 4. Write a C program to implement stack and use it to convert infix to postfix expression. 5. Write a C program for implementing a binary search tree. 6. Write a C program for implementing an expression tree. Produce its pre-order, inorder, and post-order. 7. Write a C program for implementing a double-ended queue where insertion and deletion operations are possible at both the ends. 8. Write a C program for implementing insertion operation in AVL trees. 9. Write a C program for implementation of priority queue using binary heaps. 10. Write a C program for implementing the hashing technique with open addressing. 11. Write a C program to implement Prims algorithm using priority queues to find MST of an undirected graph.

Ex. No.1(a) Aim:-

Single Linked List

To perform the basic operations on a single linked list. Algorithm:1. 2. 3. 4. Define a structure node with data and pointer as its parameter. The pointer is defined as objects of the structure. The user is asked for a choice of operation. Based on the choice the appropriate function is called.

Program:// Singly Linked List # include <stdio.h> # include <conio.h> # include <stdlib.h> # include <math.h> struct node { int data; struct node *link; }; typedef struct node NODE; NODE *start; void createemptylist(NODE *start) { start=NULL; }

void view(NODE *start) { printf("\n"); while(start!=NULL) { printf("%d->",start->data); start=start->link; } printf("NULL\n");7 } void insertfirst(int val) { NODE *ptr; ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; if(start==NULL) ptr->link=NULL; else ptr->link=start; start=ptr; }

void insertlast(int val) { NODE *ptr,*temp; ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; ptr->link=NULL; if(start==NULL) start=ptr; else { temp=start; while(temp->link!=NULL) temp=temp->link; temp->link=ptr; } } void int_at_pos(int val,int loc) { NODE *ptr,*temp; int k; temp=start; for(k=1;k<(loc-1);k++) { temp=temp->link; if(temp==NULL) { printf("NODE IN THE LIST AS LESS THAN \n"); return; } } ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; ptr->link=temp->link; temp->link=ptr; } void delfirst() { NODE *ptr; if(start==NULL) return; else {

ptr=start; start=start->link; free(ptr); } } void dellast() { NODE *ptr,*temp; if(start==NULL) return; else if(start->link==NULL) { ptr=start; start=NULL; free(ptr); } else { ptr=start; while(ptr->link!=NULL) { ptr=start; while(ptr->link!=NULL) { temp=ptr; ptr=ptr->link; } temp->link=NULL; free(ptr); } } } void delspecific(NODE * start) { NODE *ptr,*temp; int val; printf ("\n ENTER THE ELEMENT TO DELETE \n"); scanf("%d",&val); ptr=start;

if(start==NULL) {

printf("EMPTY LIST \n"); return; } else { temp=ptr; while(ptr!=NULL) { if(ptr->data==val) { temp->link=ptr->link; free(ptr); return; } temp=ptr; ptr=ptr->link; } } } void main() { int opt, item,pos; clrscr(); createemptylist(start); do { clrscr(); printf("\n***MENU***"); printf("\n1.INSERT AT BEGINNING"); printf("\n2.INSERT AT END"); printf("\n3.INSERT AT SPECIFIC POSITION"); printf("\n4.DELETE AT BEGINNING"); printf("\n5.DELETE AT END"); printf("\n6.DELETE AT SPECIFIC POSITION"); printf("\n7.VIEW"); printf("\n8.EXIT"); printf("\nCHOOSE YOUR OPTION\n"); scanf("\n%d",&opt); switch(opt) { case 1: printf("ENTER THE VALUE\n"); scanf("%d",&item); printf("\nBEFORE INSERTION\n");

view(start); insertfirst(item); printf("\nAFTER INSERTION\n"); view(start); break; case 2: printf("ENTER THE VALUE\n"); scanf("%d",&item); printf("\nBEFORE INSERTION\n"); view(start); insertlast(item); printf("\nAFTER INSERTION\n"); view(start); break; case 3: printf("ENTER THE VALUE AND POSITION\n"); scanf("%d%d",&item,&pos); printf("\nBEFORE INSERTION\n"); view(start); int_at_pos(item,pos); printf("\nAFTER INSERTION\n"); view(start); break; case 4: printf("\nBEFORE DELETION\n"); view(start); delfirst(); printf("\nAFTER DELETION\n"); view(start); break; case 5: printf("\nBEFORE DELETION\n"); view(start); dellast(); printf("\nAFTER DELETION\n"); view(start); break; case 6: printf("\nBEFORE DELETION\n"); view(start); delspecific(start); printf("\nAFTER DELETION\n"); view(start); break; case 7: printf("\nTHE ELEMENTS ARE:\n");

view(start); break; case 8: exit(0); break; default: printf("CHOOSE THE CORRECT OPTION\n"); break; } getch(); } while(opt!=8); }

Output:-

**MENU*** 1. INSERT AT BEGINNING 2. INSERT AT END 3. INSERT AT SPECIFIC POSITION 4. DELETE AT BEGINNING 5. DELETE AT END 6. DELETE AT SPECIFIC POSITION 7. VIEW 8. EXIT CHOOSE YOUR OPTION 1 ENTER THE VALUE 98 BEFORE INSERTION NUll AFTER INSERTION 98->Null **MENU*** 1.INSERT AT BEGINNING 2.INSERT AT END 3.INSERT AT SPECIFIC POSITION 4.DELETE AT BEGINNING 5.DELETE AT END 6.DELETE AT SPECIFIC POSITION 7.VIEW 8.EXIT CHOOSE YOUR OPTION 2 ENTER THE VALUE 76 BEFORE INSERTIONN 98->NUll AFTER INSERTION 98->76->NUll

Result:- Thus the program was executed and verified successfully. Ex.No.1(b) Doubly Linked List Aim:- To perform the basic operations on a doubly Linked list Algorithm:1. 2. 3. 4. 5. Create a menu Choose whether to insert or delete data in the list. Insertion accepts the data and position. Deletion gets the position of the node to be deleted. The initial creation of the list is done normally with two null pointer.

Program:// Doubly Linked List # include <stdio.h> # include <conio.h> # include <stdlib.h> # include <math.h> struct node { int data; struct node *plink; struct node *nlink; }; typedef struct node NODE; NODE *start=NULL; void createemptylist(NODE *start) { start->plink=NULL; start->nlink=NULL; }

void view(NODE *start) { printf("\n"); while(start!=NULL) { printf("%d->",start->data); start=start->nlink; } printf("NULL\n"); } void insertfirst(int val) { NODE *ptr; ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; if(start==NULL) { ptr->nlink=NULL; ptr->plink=NULL;

else ptr->nlink=start; ptr->plink=NULL; start->plink=ptr; start=ptr; } void insertlast(int val) { NODE *ptr,*temp; ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; ptr->nlink=NULL; ptr->plink=NULL; if(start==NULL) start=ptr; else { temp=start; while(temp->nlink!=NULL) temp=temp->nlink; temp->nlink=ptr; ptr->plink=temp; } } void int_at_pos(int val,int loc) { NODE *ptr,*temp; int k; temp=start; if(loc==0) { ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; ptr->nlink=temp; temp->plink=ptr; start=ptr; } else {

for(k=0;k<(loc-1);k++) { temp=temp->nlink; if(temp==NULL) { printf("NODE IN THE LIST AS LESS THAN \n"); return; } } ptr=(NODE *)malloc(sizeof(NODE)); ptr->data=val; ptr->nlink=temp->nlink; temp->nlink=ptr; ptr->plink=temp; temp->nlink->plink=ptr; } } void delfirst() { NODE *ptr; if(start==NULL) return; else { ptr=start; start=start->nlink; start->plink=NULL; free(ptr); } } void dellast() { NODE *ptr,*temp; if(start==NULL) return; else if(start->nlink==NULL) { ptr=start; start=NULL; free(ptr);

} else { ptr=start; while(ptr->nlink!=NULL) { ptr=start; while(ptr->nlink!=NULL) { temp=ptr; ptr=ptr->nlink; } temp->nlink=NULL; free(ptr); } } } void delspecific(NODE *start) { NODE *ptr,*temp; int val; printf ("\n ENTER THE ELEMENT TO DELETE \n"); scanf("%d",&val); ptr=start; if(start==NULL) { printf("EMPTY LIST \n"); return; } else { temp=ptr; while(ptr!=NULL) { if(ptr->data==val) { temp->nlink=ptr->nlink; ptr->nlink->plink=temp; free(ptr); return; } temp=ptr; ptr=ptr->nlink;

} } } void main() { int opt, item,pos; clrscr(); createemptylist(start); do { clrscr(); printf("\n***MENU***"); printf("\n1.INSERT AT BEGINNING"); printf("\n2.INSERT AT END"); printf("\n3.INSERT AT SPECIFIC POSITION"); printf("\n4.DELETE AT BEGINNING"); printf("\n5.DELETE AT END"); printf("\n6.DELETE AT SPECIFIC POSITION"); printf("\n7.VIEW"); printf("\n8.EXIT"); printf("\nCHOOSE YOUR OPTION\n"); scanf("\n%d",&opt); switch(opt) { case 1: printf("ENTER THE VALUE\n"); scanf("%d",&item); printf("\nBEFORE INSERTION\n"); view(start); insertfirst(item); printf("\nAFTER INSERTION\n"); view(start); break; case 2: printf("ENTER THE VALUE\n"); scanf("%d",&item); printf("\nBEFORE INSERTION\n"); view(start); insertlast(item); printf("\nAFTER INSERTION\n"); view(start); break; case 3: printf("ENTER THE VALUE AND POSITION\n"); scanf("%d%d",&item,&pos);

printf("\nBEFORE INSERTION\n"); view(start); int_at_pos(item,pos); printf("\nAFTER INSERTION\n"); view(start); break; case 4: printf("\nBEFORE DELETION\n"); view(start); delfirst(); printf("\nAFTER DELETION\n"); view(start); break; case 5: printf("\nBEFORE DELETION\n"); view(start); dellast(); printf("\nAFTER DELETION\n"); view(start); break; case 6: printf("\nBEFORE DELETION\n"); view(start); delspecific(start); printf("\nAFTER DELETION\n"); view(start); break; case 7: printf("\nTHE ELEMENTS ARE:\n"); view(start); break; case 8: exit(0); break; default: printf("CHOOSE THE CORRECT OPTION\n"); break; } getch(); } while(opt!=8); }

Output:-

***MENU*** 1.INSERT AT BEGINNING 2.INSERT AT END 3.INSERT ART SPECIFIC POSITION 4.DELETE AT BEGINNING 5.DELETE AT END 6.DELETE AT SPECIFIC POSITION 7.view 8.exit CHOOSE U'R OPTION 1 ENTER THE VALUE 67 before insertion NULL AFTER INSERTION 67->NULL ***MENU*** 1.INSERT AT BEGINNING 2.INSERT AT END 3.INSERT ART SPECIFIC POSITION 4.DELETE AT BEGINNING 5.DELETE AT END 6.DELETE AT SPECIFIC POSITION 7.view 8.exit CHOOSE U'R OPTION 1 ENTER THE VALUE 98 before insertion 67->NULL AFTER INSERTION 98->67->NULL

Result:Thus the program was executed and verified.

Ex. No.2 Aim:-

Polynomial Addition

To perform addition operation in the polynomial expression. Algorithm:1. Assign HEAD=NULL. 2. While (POLY1!=NULL) 3. HEAD=INSERTNODE(HEAD<COPYNODE(POLY1,1)) 4. POLY1=POLY1->NEXT 5. [End of Step 2 While Structure] 6. While (POLY2!=NULL) 7. HEAD=INSERTNODE(HEAD, COPYNODE(POLY2,1)) 8. POLY2=POLY2->next 9. [End of Step 6 While Structure] 10. Return HEAD

Program:// polynomial addition # include<stdio.h> # include<conio.h> # include<math.h> # include<malloc.h> struct link { int coeff; int pow; struct link *next; }; typedef struct link NODE; NODE *poly1,*poly2,*polyAdd;

void create(NODE *node) { char ch; do { printf("\n ENTER COEFF:"); scanf("%d",&node->coeff); printf("\n ENTER POWER:"); scanf("%d",&node->pow); node->next=(struct link*)malloc(sizeof(struct link)); node=node->next; node->next=NULL; printf("\n CONTINUE(Y/N):"); ch=getch(); }while (ch=='y'||ch=='Y'); } void display(NODE *node) { while(node->next!=NULL) { printf("%dx^%d",node->coeff,node->pow); node=node->next; if(node->next!=NULL) if(!(node->coeff<0)) printf("+");

} } void polyadd(NODE *poly1,NODE *poly2,NODE *poly) { while(poly1->next&&poly2->next) { if(poly1->pow>poly2->pow) { poly->pow=poly1->pow; poly->coeff=poly1->coeff; poly1=poly1->next; } else if(poly1->pow<poly2->pow) { poly->pow=poly2->pow; poly->coeff=poly2->coeff; poly2=poly2->next; } else { poly->pow=poly1->pow; poly->coeff=poly1->coeff+poly2->coeff; poly1=poly1->next; poly2=poly2->next; } poly->next=(struct link*)malloc(sizeof(struct link)); poly=poly->next; poly->next=NULL; } while(poly1->next||poly2->next) { if(poly1->next) { poly->pow=poly1->pow; poly->coeff=poly1->coeff; poly1=poly1->next; } if(poly2->next) { poly->pow=poly2->pow; poly->coeff=poly2->coeff; poly2=poly2->next;

} poly->next=(struct link*)malloc(sizeof(struct link)); poly=poly->next; poly->next=NULL; } } void main() { poly1=(NODE*)malloc(sizeof(NODE)); poly2=(NODE*)malloc(sizeof(NODE)); polyAdd=(NODE*)malloc(sizeof(NODE)); clrscr(); printf("\nENTER THE FIRST POLYNOMIAL:"); create(poly1); printf("\nFIRST POLYNOMIAL:"); display(poly1); printf("\nENTER THE SECOND POLYNOMIAL:"); create(poly2); printf("\nSECOND POLYNOMIAL:"); display(poly2); polyadd(poly1,poly2,polyAdd); printf("\nADDITION OF TWO POLYNOMIAL:"); display(polyAdd); getch(); }

Output:ENTER THE FIRST POLYNOMIAL: ENTER COEFF:5 ENTER POWER:4 CONTINUE(Y/N): ENTER COEFF:7 ENTER POWER:2 CONTINUE(Y/N): FIRST POLYNOMIAL:5x^4+7x^2 ENTER THE SECOND POLYNOMIAL: ENTER COEFF:8 ENTER POWER:2 CONTINUE(Y/N): ENTER COEFF:4 ENTER POWER:3 CONTINUE(Y/N): SECOND POLYNOMIAL:8x^2+4x^3 ADDITION OF TWO POLYNOMIAL:5x^4+15x^2+4x^3

Result:-

Thus the addition operation was executed and verified.

Ex. No.3:

Infix to Postfix

Aim:To convert the given infix expression into postfix. Algorithm:1. Read the infix expression one character at a time until it encounters the delimiter # 2. If the character is an operand place it on to the output. 3. If the character is an operator push it onto the stack. If the stack operator has a high or equal priority than input operator then pop that operator from the stack and place it onto the output. 4. If the character is a left parenthesis, push it onto the stack. 5. If the character is a right parenthesis, pop all the operators from the stack till it encounters left parenthesis, discard the parenthesis in the output.

Program:// Infix to Postfix #include<stdio.h> #include<ctype.h> #include<string.h> #define MAX 9 typedef struct node { char data; struct node *next; }stack; int push(char); int pop(char *); stack *getNode(); void releaseNode(stack *); void inToPost(char[],char[]); int indexpriorty(char p[],char data); stack *topStk = NULL; char ip[MAX][2]={ {'(',MAX},{')',0},{'\0',0},{'+',1}, {'-',1},{'*',2},{'/',2},{'%',2}, {'^',3} }; char sp[MAX][2]={ {'(',0},{')',-1},{'\0',0},{'+',1}, {'-',1},{'*',2},{'/',2},{'%',2}, {'^',3} }; void main() { char inStr[20], postStr[20]; clrscr(); printf("enter the infix expression :"); scanf("%s",inStr); inToPost(inStr,postStr); printf("the postfix expression is : %s",postStr); getch();

}
int push(char value) { extern stack *topStk; stack *newptr;

newptr=getNode(); if(newptr==NULL) return -1; newptr -> data = value; newptr -> next = topStk; topStk = newptr; return 0; } int pop(char *value) { extern stack *topStk; stack *temp; if(topStk == NULL) return -1; temp = topStk; topStk = topStk ->next; *value = temp -> data; releaseNode(temp); return 0; } stack *getNode() { return ((stack *)malloc(sizeof(stack)) ); } void releaseNode(stack *newnode) { free(newnode); } void inToPost(char inStr[],char postStr[]) { char ch,item; int i=0,st = 0,spr,ipr; push('\0'); while((ch = inStr[st++]) !=NULL) { if(tolower(ch) >= 'a' && tolower(ch) <='z') postStr[i++] =ch; else if(ch =='(') push(ch); else if(ch == ')') { pop(&item);

while(item !='(') { postStr[i++] = item; pop(&item); } } else { pop(&item); spr = indexpriority(sp, item); ipr = indexpriority(ip,ch); while(sp[spr][1] >= ip[ipr][1]) { postStr[i++] = item; pop(&item); spr = indexpriority(sp,item); } push(item); push(ch); } } while(!pop(&item)) postStr[i++] = item; } int indexpriority(char p[][2],char data) { int ind; for(ind =0;ind < MAX; ind++) if(p[ind][0] ==data) return ind; }

Output:-

enter the infix expression:(A+B)*(C+D)-E the postfix expression is : AB+CD+*E-

Result:-

Thus the conversion of infix to postfix was performed successfully. Ex. No. 4: Binary Search Tree Aim:To perform the basic operations in a binary search tree. Algorithm:1. Select create menu where the user can select the ADT in BST. (i) Search: The search operation is as follows: Check whether the root is NULL if so then return NULL. Otherwise check the value X with the root node value. If X is equal to T-> element, return T. If X is less than T ->element, traverse the left of T recursively. If X is greater than T-> element, traverse the right of T recursively. (ii) Insert: To insert the element X in the tree: Check with the root node T. If it is less than the root T, traverse the left subtree recursively, until T->left equals NULL, then X is placed in T->left. If it is greater than the root T, traverse the right subtree recursively, until T->right equals NULL, then X is placed in T->right. (iii) Deletion: To delete the element X in the tree, the three possibilities are * Node to be deleted is a leaf node. * Node with one child * Node with two child

Program:// Binary search tree #include<stdio.h> #include<conio.h> #include<alloc.h> #include<stdlib.h> typedef struct node { int data; struct node *left,*right; }tree; tree *getnode(); void displaymenu(); void readnode(tree*); tree *createbtree(); tree *insertnode(tree *btree,tree *temp); void releasenode(tree *head); void view(tree *btree,int level); tree *searchnode(tree *btree,int key); void main() { int choice,key; char ch; tree *temp,*btree=NULL; clrscr(); do { displaymenu(); scanf("%d",&choice); switch(choice) { case 1: btree=NULL; printf("\nCreating a new binary tree\n"); btree=createbtree(); break; case 2: printf("\nInsert a node in the binary tree\n"); temp=getnode(); readnode(temp); btree=insertnode(btree,temp); break;

case 3: if(btree==NULL) printf("\nThe binary tree is empty"); else { printf("\nSearch the node in the tree\n"); printf("\nEnter the element to be searched"); scanf("%d",&key); temp=searchnode(btree,key); if(temp==NULL) printf("\nSearched element %d not found\n",key); else printf("\nSearched element %d is found",temp->data); } break; case 4: if(btree!=NULL) { printf("\nThe binary search tree is....\n"); view(btree,1); } else printf("\nBinary tree is empty"); break; default: printf("\nEnd of run of ur program"); releasenode(btree); exit(0); } printf("\nDo u want to continue"); ch=getch(); } while(ch=='y'||ch=='Y'); } void displaymenu() { printf("\nBasic operation in a binary search tree"); printf("\n1.Create"); printf("\n2.Insert"); printf("\n3.Search "); printf("\n4.View "); printf("\n5.Exit"); printf("\nEnter your choice");

} tree *getnode() { int size; tree *newnode; size=sizeof(tree); newnode=(tree*)malloc(size); return(newnode); } void readnode(tree *newnode) { printf("\nEnter the data"); scanf("%d",&newnode->data); newnode->left=NULL; newnode->right=NULL; } tree *createbtree() { char ch; tree *temp,*btree=NULL; do { temp=getnode(); readnode(temp); btree=insertnode(btree,temp); fflush(stdin); printf("\nDo u wish to add data to the tree"); scanf("%c",&ch); } while(ch=='y'||ch=='Y'); return btree; } tree *insertnode(tree *btree,tree *temp) { if(btree==NULL) return temp; else if(temp->data<btree->data) btree->left=insertnode(btree->left,temp);

else if(temp->data>btree->data) btree->right=insertnode(btree->right,temp); else if(temp->data==btree->data) { printf("data already exist");

return btree; } return btree; } tree *searchnode(tree *btree,int key) { if(btree==NULL) return NULL; else if(key<btree->data) return searchnode(btree->left,key); else if(key>btree->data) return searchnode(btree->right,key); else if(key==btree->data) return btree; } void view(tree *btree,int level) { int k; if(btree==NULL) return; else view(btree->right,level+1); printf("\n"); for(k=0;k<level;k++) printf(" "); printf("%d\n",btree->data); view(btree->left,level+1); } void releasenode(tree *head) { free(head); }

Output:Do u wish to add data to the treey Enter the data67 Do u wish to add data to the treey Enter the data65 Do u wish to add data to the treey Enter the data82 Do u wish to add data to the treey Enter the data63 Do u wish to add data to the treey Enter the data66 Do u wish to add data to the treey Enter the data81 Do u wish to add data to the treey Enter the data89 Do u wish to add data to the treen Do u want to continue Basic operaation in a binary search tree 1.Create 2.Insert 3.Search 4.View 5.Exit Enter your choice4

The binary search tree is..... 89 82 81 67 66 65 63 Do u want to continue

Result:Thus the program was verified

Ex. No.5: Aim:-

Binary Tree Traversal

To show methods of tree traversal using Preorder, inorder and postorder. Algorithm:1. 2. 3. 4. Create a menu where the user can choose the type of traversal. Preorder traversal visits the parent node first, then the left child and finally right. Inorder visits left child, then the parent and finally right Postorder visits the right child first then left and finally parent.

Program://Binary Tree Traversal #include <stdio.h> #include <stdlib.h> #include <alloc.h> #include <conio.h> struct node { int value; struct node *left; struct node *right; }; struct node * getnode(); struct node * create(); void readnode(struct node *); struct node * insert(struct node *btree,struct node *temp); void preorder(struct node *btree); void view(struct node *btree,int level); void inorder(struct node *btree); void postorder(struct node *btree); void main() { struct node *btree=NULL, *temp; int ch; char ans; clrscr(); do { printf(" 1. Create\n 2. Insert\n 3. Preorder\n 4. Inorder\n"); printf(" 5. Postorder\n 6. view\n 7. Exit\n"); printf("Enter your choice : "); scanf("%d",&ch); switch(ch) { case 1: btree=NULL; btree=create(); break; case 2: temp=getnode(); readnode(temp); btree=insert(btree,temp); break;

case 3: if(btree!=NULL) preorder(btree); else printf("Tree is empty : "); break; case 4: if(btree!=NULL) inorder(btree); else printf("Tree is empty : "); break; case 5: if(btree!=NULL) postorder(btree); else printf("\nTree is empty : \n"); break; case 6: if(btree!=NULL) { printf("The Binary search tree is...."); view(btree,1); } else printf("The binary tree is empty"); break; default: exit(0); } printf("\nDo u want to continue\n"); ans=getch(); } while(ans=='y'||ans=='Y'); } struct node * getnode() { struct node * newnode; newnode=(struct node *) malloc(sizeof(struct node)); return newnode; } void readnode(struct node *newnode) {

printf("Enter the value : "); scanf("%d",&newnode->value); newnode->left=NULL; newnode->right=NULL; } struct node * create() { char ch; struct node *btree=NULL,*temp; do { temp=getnode(); readnode(temp); btree=insert(btree,temp); fflush(stdin); printf("\nDo u wis to add data : "); scanf("%c",&ch); }while(ch=='y'||ch=='Y'); return btree; } struct node * insert(struct node *btree,struct node *temp) { if(btree==NULL) return temp; else if(temp->value < btree->value) btree->left=insert(btree->left,temp); else if(temp->value > btree->value) btree->right=insert(btree->right,temp); else if(temp->value == btree->value) { printf("Data already exists ...\n"); return(btree); } return(btree); } void inorder(struct node *btree) { if(btree!=NULL) { inorder(btree->left); printf("%d\t",btree->value); inorder(btree->right);

} } void preorder(struct node *btree) { if(btree!=NULL) { printf("%d\t",btree->value); preorder(btree->left); preorder(btree->right); } } void postorder(struct node *btree) { if(btree!=NULL) { postorder(btree->left); postorder(btree->right); printf("%d\t",btree->value); } } void view(struct node *btree,int level) { int k; if(btree==NULL) return; view(btree->right,level+1); printf("\n"); for(k=0;k<level;k++) printf(" "); printf("%d\n",btree->value); view(btree->left,level+1); }

Output:1. create 2. insert 3. preorder 4. inorder 5. postorder 6. view 7. exit 1 Enter the value: 34 do u want to continue 1. create 2. insert 3. preorder 4. inorder 5. postorder 6. view 7. exit 2 enter the value:66 do u want to continue 1. create 2. insert 3. preorder 4. inorder 5. postorder 6. view 7. exit 2 enter the value:22 do u want to continue 1. create 2. insert 3. preorder 4. inorder 5. postorder 6. view 7. exit 6

the binary search tree is .... 66 34 22 do u want to continue 1. create 2. insert 3. preorder 4. inorder 5. postorder 6. view 7. exit 3 34 22 66 do u want to continue

Result:-

Thus the program was verified. Ex. No.6: Doubly Ended Queue Aim:To perform the insertion and deletion operation at both the ends in a queue. Algorithm:1. Create a menu 2. Choose whether to insert or delete the data in the queue. 3. Insertion takes place at both the ends such as front and rear. 4. Similarly deletion takes place at both the ends. 5. Based on the operations the appropriate function is called.

Program:// Doubly Ended Queue #include<stdio.h> #include<conio.h> #include<stdlib.h> #define QSIZE 5 void displayMenu(); int isEmpty(); int isFull(); int enqueueRear(int value); int dequeueRear(int *value); int enqueueFront(int value); int dequeueFront(int *value); int size(); void view(); int queue[QSIZE],front=-1,rear=-1; void main() { int status,choice,data; clrscr(); displayMenu(); while(1) { printf("\nEnter ur choice:"); scanf("%d",&choice); switch(choice) { case 0: displayMenu(); break; case 1: printf("\nEnter the element:"); scanf("%d",&data); status=enqueueFront(data); if(status==-1) printf("Deque Overflow on Enqueue at front..."); break; case 2: printf("\nEnter the element:"); scanf("%d",&data); status=enqueueRear(data); if(status==-1) printf("Deque Overflow on Enqueue at rear..."); break; case 3:

status=dequeueFront(&data); if(status==-1) printf("Deque Underflow on Dequeue at front..."); else printf("\n The dequeued value is %d",data); break; case 4: status=dequeueRear(&data); if(status==-1) printf("\nDeque Underflow on Dequeue at rear..."); else printf("\n The dequeued value is %d",data); break; case 5: printf("Number of elements in Deque is %d",size()); break; case 6: view(); break; default: printf("\n End of run of your program..."); exit(0); } } getch(); } void displayMenu() { printf("\n Representation of Linear Deque using arrays..."); printf("\n\t 0.View Menu"); printf("\n\t 1.Enqueue at Front"); printf("\n\t 2.Enqueue at Rear"); printf("\n\t 3.Dequeue at Front"); printf("\n\t 4.Dequeue at Rear"); printf("\n\t 5.Size of the queue"); printf("\n\t 6.View"); printf("\n\t 7.Exit"); } int isEmpty() { extern int queue[],front,rear; if(front==-1 && rear==-1) return 1; else return 0; }

int isFull() { extern int queue[],front,rear; if(rear==(QSIZE -1)) return 1; else return 0; } int enqueueFront(int value) { extern int queue[],front,rear; if(isEmpty()) front=rear=0; else if(isFull()) return -1; else front= front-1; queue[front]=value; return 0; } int enqueueRear(int value) { extern int queue[],front,rear; if(isEmpty()) front=rear=0; else if(isFull()) return -1; else rear=rear+1; queue[rear]=value; return 0; } int dequeueFront(int *value) { extern int queue[],front,rear; if(isEmpty()) return -1; *value=queue[front]; if(front==rear) front=rear=-1; else front=front+1; return 0; } int dequeueRear(int *value)

{ extern int queue[],front,rear; if(isEmpty()) return -1; *value=queue[rear]; if(front==rear) front=rear=-1; else rear=rear-1; return 0; } int size() { extern int queue[],front,rear; if(isEmpty()) return 0; return(rear-front+1); } void view() { extern int q1ueue[],front,rear; int f; if(isEmpty()) { printf("\n Deque is Empty!!!"); return; } printf("\n Content of the deque is...\n FRONT-->"); for(f=front;f!=rear;f=f+1) printf(" %d ",queue[f]); printf("%d<--REAR",queue[f]); if(isFull()) printf("\n Deque is FULL!!!"); }

Output:-

Representation of Linear Deque using arrays... 0.View Menu 1.Enqueue at Front 2.Enqueue at Rear 3.Dequeue at Front 4.Dequeue at Rear 5.Size of the queue 6.View 7.Exit Enter ur choice:1 Enter the element:23 Enter ur choice:6 Content of the deque is... FRONT-->23<--REAR Enter ur choice:2 Enter the element:50 Enter ur choice:6 Content of the deque is... FRONT--> 23 50<--REAR Enter ur choice:1 Enter the element:45 Enter ur choice:6 Content of the deque is... FRONT--> 45 23 50<--REAR Enter ur choice:3 The dequeued value is 45 Enter ur choice:6 Content of the deque is... FRONT--> 23 50<--REAR Enter ur choice:4

The dequeued value is 50 Enter ur choice:6 Content of the deque is... FRONT-->23<--REAR Enter ur choice:

Result:Thus the program was verified.

Ex. No.7 Aim:-

AVL

To perform the basic operations on a BST Algorithm:1. In an AVL tree at each node an associated balance factor indicating the relative heights of its left and right sub trees. 2. The balance factor should be -1,0 or +1 for all the nodes. 3. Insertion and deletion into the tree will be analyzed. 4. If it violates, then we need to reorganize the tree by a series of rotations to make it balanced.

Program://AVL Tree #include<stdio.h> #include<conio.h> #include<malloc.h> #define CHANGED 0 #define BALANCED 1 typedef struct bnode { int data,bfactor; struct bnode *left,*right; }node; node *getNode(); void copyNode(node *r,int data); void releaseNode(node *p); void displayMenu(); node *searchNode(node *root,int data); node *insertNode(int data, node *p); void RightHeavyBalance(node **Pptr); void LeftToLeft(node **Pptr, node **Aptr); void LeftToRight(node **Pptr, node **Aptr, node **Bptr); void RightToRight(node **Pptr, node **Aptr); void RightToLeft(node **Pptr, node **Aptr, node **Bptr); void view(node *root,int level); int height; node *getNode() { int size; node *newnode; size=sizeof(node); newnode=(node *)malloc(size); return(newnode); } void main() { int data,ch,choice='y'; clrscr(); node *root=NULL; displayMenu(); while((choice=='Y')||(choice=='y')) { printf("\n?"); fflush(stdin);

scanf("%d",&ch); switch(ch) { case 0: displayMenu(); break; case 1: printf("\n Enter the value to be inserted:"); scanf("%d",&data); if(searchNode(root,data)==NULL) root=insertNode(data,root); else printf("\n Data is already exists"); break; case 2: if(root==NULL) { printf("\n AVL tree is Empty\n"); continue; } printf("\n AVL tree is:\n"); view(root,1); break; default: printf("\nEnd of Run of your program..."); releaseNode(root); return; } } getch(); } void displayMenu() { printf("\n Basic operations in an AVL Tree..."); printf("\n 0. Display Menu List"); printf("\n 1. Insert a Node in the AVL Tree"); printf("\n 2. View the AVL Tree"); printf("\n 3. Exit"); } void copyNode(node *r, int data) { r->data=data; r->left=NULL; r->right=NULL; r->bfactor=0; }

void releaseNode(node *p) { free(p); } node *searchNode(node *root,int data) { if(root!=NULL) if(data<root->data) root=searchNode(root->left,data); else if(data>root->data) root=searchNode(root->right,data); return(root); } node *insertNode(int data,node *p) { node *A,*B; if(p==NULL) { p=getNode(); copyNode(p,data); height=CHANGED; return(p); } if(data<p->data) { p->left=insertNode(data,p->left); if(height==CHANGED) { switch(p->bfactor) { case -1: p->bfactor=0; height=BALANCED; break; case 0: p->bfactor=1; break; case 1: A=p->left; if(A->bfactor==1) LeftToLeft(&p,&A); else LeftToRight(&p,&A,&B); height=BALANCED; break; }

} } if(data>p->data) { p->right=insertNode(data,p->right); if(height==CHANGED) { switch(p->bfactor) { case 1: p->bfactor=0; height=BALANCED; break; case 0: p->bfactor=-1; break; case -1: A=p->right; if(A->bfactor==-1) RightToRight(&p,&A); else RightToLeft(&p,&A,&B); height=BALANCED; break; } } } return(p); } void LeftToLeft(node **Pptr,node **Aptr) { node *p=*Pptr,*A=*Aptr; printf("\n Left to Left AVL Rotation \n"); p->left=A->right; A->right=p; if(A->bfactor==0) { p->bfactor=1; A->bfactor=-1; height=BALANCED; } else { p->bfactor=0;

A->bfactor=0; } p=A; *Pptr=p; *Aptr=A; } void LeftToRight(node **Pptr,node **Aptr,node **Bptr) { node *p=*Pptr,*A=*Aptr,*B=*Bptr; printf("\n Left to Right AVL Rotation \n"); B=A->right; A->right=B->left; B->left=A; p->left=B->right; B->right=p; if(B->bfactor==1) p->bfactor=-1; else p->bfactor=0; if(B->bfactor==-1) A->bfactor=1; else A->bfactor=0; B->bfactor=0; p=B; *Pptr=p; *Aptr=A; *Bptr=B; } void RightToRight(node **Pptr,node **Aptr) { node *p=*Pptr,*A=*Aptr; printf("\n Right to Right AVL Rotation \n"); p->right=A->left; A->left=p; if(A->bfactor==0) { p->bfactor=-1; A->bfactor=1; height=BALANCED; } else { p->bfactor=0; A->bfactor=0; }

p=A; *Pptr=p; *Aptr=A; } void RightToLeft(node **Pptr,node **Aptr,node **Bptr) { node *p=*Pptr,*A=*Aptr,*B=*Bptr; printf("\n Right to left AVL Rotation \n"); B=A->left; A->left=B->right; B->right=A; p->right=B->left; B->left=p; if(B->bfactor==-1) p->bfactor=1; else p->bfactor=0; if(B->bfactor==1) A->bfactor=-1; else A->bfactor=0; B->bfactor=0; p=B; *Pptr=p; *Aptr=A; *Bptr=B; } void view(node *root, int level) { int k; if(root==NULL) return; view(root->right,level+1); printf("\n"); for(k=0;k<level;k++) printf(" "); printf("%d",root->data); view(root->left,level+1); }

Output:Basic operations in an AVL Tree 0.Display a Menu List 1. Insert a Node in the AVL Tree 2. View the AVL Tree 3. Exit ?1 Enter the value to be inserted:45 ?1 Enter the value to be inserted:78 ?1 Enter the value to be inserted:35

?2 AVL tree is: 78 45 35 ?1 Enter the value to be inserted:12 ?1 Enter the value to be inserted:7 Left to Left AVL Rotation ?2 AVL tree is: 78 45 35 12 7

?1

Enter the value to be inserted:82 ?1 Enter the value to be inserted:97 Right to Right AVL Rotation ?2 AVL tree is: 97 82 78 45 35 12 7 ?

Result:Thus the program was executed and verified.

Ex. No:8 Aim:-

Priority Queue using Binary Heaps

To implement priority queue using binary heaps Algorithm:1. Create a menu. 2. A heap must satisfy the heap property, which says that the priority of every node is greater than or equal to the priority of any child nodes of that node. 3. The root node contains the item that is at the head of the queue. 4. In order to use a heap to implement a priority queue, we need to implement the heaps insert or remove operations in terms of operations on the heap. 5. When we add a new item to the heap, a new node must be added in the next available position, at the end of the array. 6. If the new item has high priority, swap it with its parent. 7. Now the new item might still be out of place in its new position, so we have another contest between it and its new parent. 8. Repeat this process until the new item is in correct position in the heap or reaches the root node.

Program:-

// Priority queue using Binary Heaps #include<stdio.h> #include<conio.h> #define SIZE 5 void main(void) { int rear,front,que[SIZE],choice; int qfull(int rear),qempty(int rear,int front); int insert(int que[SIZE],int rear,int front); int delete(int que[SIZE],int front); void display(int que[SIZE],int rear,int front); char ans; clrscr(); front=0; rear=-1; do { clrscr(); printf("\n\t\t Priority Queue\n"); printf("\n Main Menu"); printf("\n1.Insert\n2.Delete\n3.Display"); printf("\nEnter Your Choice:"); scanf("%d",&choice); switch(choice) { case 1: if(qfull(rear)) printf("\n Queue is dull"); else rear=insert(que,rear,front); break; case 2: if(qempty(rear,front)) printf("\n Cannot delete element"); else front=delete(que,front); break; case 3: if(qempty(rear,front)) printf("\n Queue is emrty"); else

display(que,rear,front); break; default: exit(0); }

printf("\n Do You want to continue?"); ans=getche(); } while(ans=='Y' || ans=='y'); getch(); } int insert(int que[SIZE],int rear,int front) { int item,j; printf("\n Enter the element:"); scanf("%d",&item); if(front==-1) front++; j=rear; while(j>=0 && item < que[j]) { que[j+1]=que[j]; j--; } que[j+1]=item; rear=rear+1; return rear; } int qfull(int rear) { if(rear==SIZE-1) return 1; else return 0; } int delete(int que[SIZE],int front) { int item; item=que[front]; printf("\n The item deleted is %d",item); front++; return front; }

qempty(int rear,int front) { if((front==-1)||(front>rear)) return 1; else return 0; }

void display(int que[SIZE],int rear,int front) { int i; printf("\n The queue is:"); for(i=front;i<=rear;i++) printf(" %d",que[i]); }

Output:-

Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice:1 Enter the element:50 Do You want to continue? Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice:1 Enter the element:43 Do You want to continue? Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice:1 Enter the element:32 Do You want to continue? Priority Queue Main Menu 1.Insert 2.Delete 3.Display

Enter Your Choice:3 The queue is: 32 43 50 Do You want to continue?

Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice:2 The item deleted is 32 Do You want to continue? Priority Queue Main Menu 1.Insert 2.Delete 3.Display The queue is: 43 50 Do You want to continue?

Result:Thus the program was written to implement a priority queue using a heap.

Ex. No. 9 Aim:-

Hashing with open Addressing

To implement the hashing technique using open addressing. Algorithm:1. Let the keys to be mapped in the hash table using division function method. 2. To resolve collision the hashing function is resolved by placing the record in the next available empty position in the hash table. 3. If the hashed address mapped by the key is already occupied then the next empty position is assigned to the key. 4. Since this method, searches for the empty position, in a linear way.

Program:-

//Hashing with Open addressing #include<stdio.h> #include<conio.h> #include<stdlib.h> #define MAX 10 void main() { int a[MAX],num,key,i; char ans; int create(int); void linear_prob(int[],int,int),display(int[]); clrscr(); printf("\nCollision 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("\n Do U want to Continue?(y/n): "); ans=getche(); }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) { if(a[i]!=-1) count++; i++; } if(count==MAX) { printf("\n Hash 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("\n The Hash Table is...\n"); for(i=0;i<MAX;i++) printf("\n %d %d",i,a[i]); }

Output: Collision Handling By Linear Probing Enter the number: 131 Do U want to Continue?(y/n): y Enter the number: 21 Do U want to Continue?(y/n): y Enter the number: 3 Do U want to Continue?(y/n): y Enter the number: 4 Do U want to Continue?(y/n): y Enter the number: 5 Do U want to Continue?(y/n): y Enter the number: 8 Do U want to Continue?(y/n): y Enter the number: 9 Do U want to Continue?(y/n): y Enter the number: 18 Do U want to Continue?(y/n):n The Hash Table is 0 1 2 3 4 5 6 7 8 9 18 131 21 3 4 5 -1 -1 8 9

Result:-

Thus the hashing technique using open addressing was executed Ex. No.10 Prims using Priority Queue Aim: To implement Prims algorithm using priority queue to find an MST of an undirected graph. Algorithm:1. Consider any vertex in the graph. Process the vertex and add the vertex and the vertex to the tree. 2. Find the smallest edge from the graph connecting the edge of the vertex in the tree. Such that is doesnt form a cycle. 3. Add that vertex to the tree. 4. Repeat Step 2, until the tree contains all the n vertices.

Program: //Prims using Priority Queue #include<stdio.h> #include<conio.h> #define SIZE 20 #define INFINITY 32767 void prim(int g[][SIZE],int nodes) { int q[SIZE],i,j,k; int min_dist,v1,v2,tot=0; for(i=0;i<nodes;i++) q[i]=0; printf("\n\n The Minimal Spanning Tree is:\n"); q[0]=1; for(k=1;k<nodes;k++) { min_dist=INFINITY; for(i=0;i<nodes;i++) { for(j=0;j<nodes;j++) { if(g[i][j]&&((q[i]&& !q[j])|| (!q[i] && q[j]))) { if(g[i][j]<min_dist) { min_dist=g[i][j]; v1=i; v2=j; } } } } printf("\n Edge(%d %d) and weight= %d",v1,v2,min_dist); q[v1]=q[v2]=1; tot=tot+min_dist; } printf("\n \n \t Total path Length Is=%d",tot); } void main() { int g[SIZE][SIZE],nodes; int v1,v2,length,i,j,n;

clrscr(); printf("\n\tPrim's Algorithm\n"); printf("\n Enter Number Of Nodes in the Graph"); scanf("%d",&nodes); printf("\n Enter Number Of Edges in the Graph"); scanf("%d",&n); for(i=0;i<nodes;i++) for(j=0;j<nodes;j++) g[i][j]=0; printf("\n Enter edges and weights\n"); for(i=0;i<n;i++) { printf("\n Enter edge by V1 and V2:"); scanf("%d%d",&v1,&v2); printf("\n Enter corresponding Weight:"); scanf("%d",&length); g[v1][v2]=g[v2][v1]=length; } printf("\n\t"); clrscr(); prim(g,nodes); getch(); }

Output:Prim's Algorithm Enter Number Of Nodes in the Graph 7 Enter Number Of Edges in the Graph 9 Enter edges and weights Enter edge by V1 and V2: 0 1 Enter corresponding Weight: 27 Enter edge by V1 and V2: 1 2 Enter corresponding Weight: 16 Enter edge by V1 and V2: 2 3 Enter corresponding Weight: 12 Enter edge by V1 and V2: 3 4 Enter corresponding Weight: 22 Enter edge by V1 and V2: 4 5 Enter corresponding Weight: 25 Enter edge by V1 and V2: 0 5 Enter corresponding Weight: 6 Enter edge by V1 and V2: 1 6 Enter corresponding Weight:14 Enter edge by V1 and V2: 4 6 Enter corresponding Weight: 24 Enter edge by V1 and V2: 3 6 Enter corresponding Weight:18

The Minimal Spanning Tree is: Edge(0 5) and weight= 6 Edge(4 5) and weight= 25 Edge(3 4) and weight= 22 Edge(2 3) and weight= 12 Edge(1 2) and weight= 16 Edge(1 6) and weight= 14 Total path Length Is=95

Result:Thus the prims algorithm using priority queue was executed and verified.

You might also like