You are on page 1of 46

List of Experiments S.NO 1.a 1.b 2. 3. 4. 5. 6. 7. 8. 9. 10.

NAME OF THE PROGRAM Implement singly linked list Implement doubly linked list. Represent a polynomial as a linked list and write functions for polynomial addition. Implement stack and use it to convert infix to postfix expression Implement array-based circular queue and use it to simulate a producer-consumer problem. Implement an expression tree. Produce its pre-order, in-order, and post-order traversals. Implement binary search tree. Implement priority queue using heaps Implement hashing techniques Implement Dijkstra's algorithm using priority queues Implement a backtracking algorithm for Knapsack problem PAGE NO

Ex No:1a

Implementation of singly linked lists

Aim To write a C program to implement List ADT using Linked List. Algorithm

Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the next element in the structure. Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the list functions. Step 3:- Declare necessary pointer variables as struct node data type. Step 4:- Get a choice from the user. If the choice is create, Get first data from the user by calling the function create( ), and display contents of the list. Step 5:- If the choice is insert, Get data and its position by calling the function insert( ), and assign the LINK field of the given data node according to the position. Display the contents of the list. Step 6:- If the choice is delete, get the position of the data which is going to be removed from the list and assign LINK field of the previous node to the address of the next node. Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit. Step 8:- Terminate the execution. Program #include<stdio.h> #include<conio.h> #include<alloc.h> void create(); void insert(); void del(); void display(); struct node { int data; struct node *link; }; struct node *first=NULL,*last=NULL,*next,*prev,*cur; void create() { cur=(struct node *)malloc(sizeof(struct node)); printf("enter the data:"); scanf("%d",&cur->data); cur->link=NULL; first=cur; last=cur; } void insert() { int pos,c=1; cur=(struct node*)malloc(sizeof(struct node)); printf("enter the data:"); scanf("%d",&cur->data); printf("Enter the position:"); scanf("%d",&pos); if(pos==1&&first!=NULL)

{ cur->link=first; first=cur; } else { next=first; while( c<pos) { prev=next; next=prev->link; c++; } if(prev==NULL) { printf("invalid position"); } else { cur->link=prev->link; prev->link=cur; } } } void del() { int pos,c=1; printf("Enter the position to be deleted"); scanf("%d",&pos); if(first==NULL) { printf("list is empty"); } else if(pos==1 && first->link==NULL) { printf("Deleted element is %d",first->data); free(first); first=NULL; } else if(pos==1 && first->link!=NULL) { cur=first; first=first->link; cur->link=NULL;

printf("Deleted element is %d",cur->data); free(cur); } else { next=first; while(c<pos) { cur=next; next=next->link; c++; } cur->link=next->link; next->link=NULL; if(next==NULL) { printf("invalid position"); } else { printf("Deleted element is %d",next->data); free(next); } } } void display() { cur=first; printf("\n The elements in the list are:"); while(cur!=NULL) { printf("%d\t",cur->data); cur=cur->link; } } void main() { int ch; clrscr(); printf("singly linked list:"); do { printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Exit"); printf("\n\nEnter your option"); scanf("%d",&ch); switch(ch)

{ case 1: create(); display(); break; case 2: insert(); display(); break; case 3: del(); display(); break; case 4: exit(0); } } while(ch<=3); } Output Singly linked list: 1.Create 2.Insert 3.Delete 4.Exit Enter your option1 Enter the data:1 The elements in the list are:1 1.Create 2.Insert 3.Delete 4.Exit Enter your option2 Enter the data:4 Enter the position:2 The elements in the list are:1 4 1.Create 2.Insert 3.Delete 4.Exit Enter your option 2 Enter the data:7 Enter the position:3 The elements in the list are:1 47 1. Create

2.Insert 3.Delete 4.Exit Enter your option 3 Enter the position to be deleted2 Deleted element is 4 The elements in the list are:17 1.Create 2.Insert 3.Delete 4.Exit Enter your option 4

Ex No:1b

Implementation of doubly linked lists.

Aim To write a C program to implement doubly Linked List. Algorithm Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the next element in the structure. Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the list functions. Step 3:- Declare necessary pointer variables as struct node data type. Step 4:- Get a choice from the user. If the choice is create, Get first data from the user by calling the function create( ), and display contents of the list. Step 5:- If the choice is insert, Get data and its position by calling the function insert( ), and assign the LINK field of the given data node according to the position. Display the contents of the list. Step 6:- If the choice is delete, get the position of the data which is going to be removed from the list and assign LINK field of the previous node to the address of the next node. Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit. Step 8:- Terminate the execution.

Program
#include<stdio.h> #include<conio.h> #include<alloc.h> void create(); void insert(); void del(); void display(); struct node { int data; struct node *flink,*blink; }; struct node *first=NULL,*last=NULL,*next,*prev,*cur; void create() {

cur=(struct node *)malloc(sizeof(struct node)); printf("Enter the data:"); scanf("%d",&cur->data); cur->flink=NULL; cur->blink=NULL; first=cur; last=cur; } void insert() { int pos,c=1; cur=(struct node*)malloc(sizeof(struct node)); printf("Enter the data:"); scanf("%d",&cur->data); printf("Enter the position:"); scanf("%d",&pos); if(pos==1&&first!=NULL) { cur->flink=first; cur->blink=NULL; first->blink=cur; first=cur; } else { next=first; while( c<pos) { prev=next; next=prev->flink; c++; } if(prev==NULL) { printf("Invalid position"); } else { cur->flink=prev->flink; cur->blink=prev; prev->flink->blink=cur; prev->flink=cur; } } } void del()

{ int pos,c=1; printf("Enter the position to be deleted"); scanf("%d",&pos); if(first==NULL) { printf("DLL is empty"); } else if(pos==1 && first->flink==NULL) { printf("Deleted element is %d",first->data); free(first); first=NULL; last=NULL; } else if(pos==1 && first->flink!=NULL) { cur=first; first=first->flink; cur->flink=NULL; first->blink=NULL; } else { next=first; while(c<pos) { cur=next; next=next->flink; c++; } if(next==NULL) { printf("Invalid position"); } else { cur->flink=next->flink; next->flink->blink=cur; next->flink=NULL; next->blink=NULL; printf("Deleted element is %d",next->data); free(next); }

} } void display() { cur=first; printf("\n The elements in the list are:"); while(cur!=NULL) { printf("%d\t",cur->data); cur=cur->flink; } } void main() { int ch; clrscr(); printf("Doubly linked list:"); do { printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Exit"); printf("\n\nEnter your option"); scanf("%d",&ch); switch(ch) { case 1: create(); display(); break; case 2: insert(); display(); break; case 3: del(); display(); break; case 4: exit(0); } } while(ch<=3); } Output Doubly linked list: 1.Create

2.Insert 3.Delete 4.Exit Enter your option 1 Enter the data:1 The elements in the list are:1 1.Create 2.Insert 3.Delete 4.Exit Enter your option2 Enter the data:4 Enter the position:2 The elements in the list are:1 4 1.Create 2.Insert 3.Delete 4.Exit Enter your option 2 Enter the data:7 Enter the position:3 The elements in the list are:1 4 7 1.Create 2.Insert 3.Delete 4.Exit Enter your option3 Enter the position:3 The elements in the list are:1 4 1.Create 2.Insert 3.Delete 4.Exit Enter your option 4

Ex No:2 Addition of two polynomial using linked list Aim


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

Algorithm
Addition of two polynomials Consider addition of the following polynomials 5 x12 + 2 x9 + 4x7 + 6x6 + x3 7 x8 + 2 x7 + 8x6 + 6x4 + 2x2 + 3 x + 40 The resulting polynomial is going to be 5 x12 + 2 x9 + 7 x8 + 6 x7 + 14x6 + 6x4 +x3 2x2 + 3 x + 40 Step 1: We started with the highest power in any polynomial. If there was no item having same exponent, we simply appended the term to the new list, and continued with the process.

Step 2: Wherever we found that the exponents were matching, we simply added the coefficients and then stored the term in the new list. Step 3: If one list gets exhausted earlier and the other list still contains some lower order terms, then simply append the remaining terms to the new list. Step 4: Let phead1, phead2 and phead3 represent the pointers of the three lists under consideration. Step 5: Let each node contain two integers exp and coff . Step 6: Let us assume that the two linked lists already contain relevant data about the two polynomials.Also assume that we have got a function append to insert a new node at the end of the given list.

Program
#include<stdio.h> #include<malloc.h> #include<conio.h> struct link { int coeff; int pow; struct link *next; }; struct link *poly1=NULL,*poly2=NULL,*poly=NULL; void create(struct link *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 show(struct link *node) { while(node->next!=NULL) { printf("%dx^%d",node->coeff,node->pow); node=node->next; if(node->next!=NULL)

printf("+"); } } void polyadd(struct link *poly1,struct link *poly2,struct link *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; } } main() { char ch; do { poly1=(struct link *)malloc(sizeof(struct link)); poly2=(struct link *)malloc(sizeof(struct link)); poly=(struct link *)malloc(sizeof(struct link)); printf("\nEnter 1st number:"); create(poly1); printf("\nEnter 2nd number:"); create(poly2); printf("\n1st Number:"); show(poly1); printf("\n2nd Number:"); show(poly2); polyadd(poly1,poly2,poly); printf("\nAdded polynomial:"); show(poly); printf("\n Add two more numbers:"); ch=getch(); } while(ch=='y' || ch=='Y'); }

Output
Enter 1st number: Enter coeff:2 Enter power:2 Continue(y/n):y Enter coeff:2 Enter power:1 Continue(y/n):y Enter coeff:2 Enter power:0 Continue(y/n):n Enter 2nd number: Enter coeff:1 Enter power:2 Continue(y/n):y Enter coeff:1 Enter power:1 Continue(y/n):y Enter coeff:1

Enter power:0 1st Number:2x^2+2x^1+2x^0 2nd Number:1x^2+1x^1+1x^0 Added polynomial:3x^2+3x^1+3x^0 Add two more numbers: n

Ex No: 3 Implement a stack and use it to convert infix to postfix expression Aim
To write a C program to implement a stack and convert the infix expression to postfix expression .

Algorithm
Step 1:- Make an empty Stack. Step 2:- Read an expression. Step 3:- Scan the expression from left to right and repeat steps 2 & 3 for each element in the expression. Step 4:- If an operand is encountered, push it on to the stack. Step 5:- If an operator is encounters, then a) Remove the two top elements from the stack. b) Perform the required operation. c) Place the result back on to the stack. Step 6:- Set value equal to the top most element on stack. Step 7:- Terminate the execution.

Program
#include<stdio.h> #include<conio.h> int stack[20],top=0; char intr[40],post[40]; void push(); char pop(); void postfix() { int i,j=0; for(i=0;intr[i]!=NULL;i++) { switch(intr[i]) { case'+':while(stack[top]>=1) post[j++]=pop(); push(1); break; case'-':while(stack[top]>=2) post[j++]=pop(); push(2); break; case'*':while(stack[top]>=3) post[j++]=pop(); push(3);

break; case'/':while(stack[top]>=4) post[j++]=pop(); push(4); break; case'^':while(stack[top]>=5) post[j++]=pop(); push(5); break; case'(':push(0); break; case')':while(stack[top]!=0) post[j++]=pop(); top--; break; default: post[j++]=intr[i]; } } while(top>0) post[j++]=pop(); printf("\n Post fix expression is:: %s",post); } void push(int de) { top++; stack[top]=de; } char pop() { char e; e=stack[top]; top--; switch(e) { case 1:e='+'; break; case 2:e='-'; break; case 3:e='*'; break; case 4:e='/';

break; case 5:e='^'; break; } return(e); } void main() { clrscr(); printf("\n\t\t*********** Infix to postfix******************"); printf("\nEnter the infix expression"); scanf("%s",intr); postfix(); getch(); } Output: *********** Infix to postfix****************** Enter the infix expression ((a*b)+(b*c)/(c*d)) Post fix expression is:: ab*bc*cd*/+

Ex No:4 Implement an array based circular queue and use it to simulate a producer-consumer problem. Aim:
To implement array based circular queue and use it to simulate a producer-consumer problem.

Algorithm for Insertion


Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3 Step-2: Make the "rear" value as 0 Step-3: Increment the "rear" value by one Step-4: 1. 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-4. 2. Insert the new value for the queue position pointed by the "rear"

Algorithm for deletion


Step-1: If the queue is empty then say "empty queue" and quit; else continue Step-2: Delete the "front" element Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5 Step-4: Make the "front" point to the first position in the queue and quit Step-5: Increment the "front" position by one Program #include<stdio.h> #include<conio.h> #include<process.h> #include<alloc.h>

#define size 3 char cqueue[size]; int front=-1,rear; void producer_enqueue(int element); int consumer_dequeue(); void main() { int ch,elem; char c; clrscr(); do { printf("\n\t\t\t\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n"); printf("ENTER YOUR CHOICE"); scanf("%d",&ch); switch(ch) { case 1: printf("\n enter the element"); scanf("%d",&elem); producer_enqueue(elem); break; case 2: elem=consumer_dequeue(); if(elem!=-1) printf("\consumer element is %d",elem); break; case 3: exit(0); } printf("\nCONTINUE Y/N ?\n"); c=getch(); }while(c=='y'||c=='Y'); } void producer_enqueue(int element) { if(front==(rear+1)%size) { printf("\n consumer queue is full\n"); } else { if(front==-1) front=rear=0; else rear=(rear+1)%size;

cqueue[rear]=element; } } int consumer_dequeue() { int element=-1; if(front==-1) { printf("\n the consumer queue is empty\n"); } else { element=cqueue[front]; if(front==rear) front=rear=-1; else front=(front+1)%size; } return element; } Output: 1.PRODUCER 2.CONSUMER 3.EXIT ENTER YOUR CHOICE 1 enter the element1 CONTINUE Y/N ? 1.PRODUCER 2.CONSUMER 3.EXIT ENTER YOUR CHOICE 1 enter the element4 CONTINUE Y/N ? 1.PRODUCER 2.CONSUMER 3.EXIT ENTER YOUR CHOICE 2 consumer element is 1 CONTINUE Y/N ?

Ex No:5 Implement an expression tree and produce its pre-order, in-order, and post-order traversals.
Aim: To implement an expression tree and produce its pre-order, in-order, and post-order traversals. Algorithm:

a. To traverse a non-empty binary tree in preorder, perform the following operations

recursively at each node, starting with the root node: 1. Visit the root. 2. Traverse the left subtree. 3. Traverse the right subtree. b. To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Visit the root. 3. Traverse the right subtree c. To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Traverse the right subtree. 3. Visit the root

Program
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void push(struct enode*); struct enode* pop(void); void infix(struct enode*); void prefix(struct enode*); void postfix(struct enode*); char equation[25]; struct enode* stack[25]; int top = -1; struct enode { char item; struct enode* lchild; struct enode* rchild; }*root; int main(void) { int count; char ch; printf("\n\nEnter equation in the form of postfix: "); gets(equation); printf("\nYou have entered: "); puts(equation); for(count = 0; equation[count] != '\0'; count++) { ch=equation[count]; if(isalpha(ch))

{ root = (struct enode*)malloc(sizeof(struct enode)); root->item = ch; root->rchild = NULL; root->lchild = NULL; push(root); } else if(ispunct(ch)) { root = (struct enode*)malloc(sizeof(struct enode)); root->item = ch; root->rchild = pop(); root->lchild = pop(); push(root); } else { printf("\nSorry unrecognized entry"); } } while(1) { printf("\nSelect the output form:\n 1) [i]nfix\n 2) p[r]efix\n 3) p[o]stfix \n 4) e[x]it\nEnter u r choice: "); ch = getche(); printf("\n"); switch(ch) { case 'i': printf("\nInorder representation of output is: "); infix(stack[top]); break; case 'r': printf("\nPreorder representation of output is: "); prefix(stack[top]); break; case 'o': printf("\nPostorder representation of output is: "); postfix(stack[top]); break; case 'x': printf("\nYou have pressed the button other than given choices"); exit(0);

default: printf("\nENTER THE CORRECT OPTION"); } getch(); } } void infix(struct enode* root) { if(root->lchild != NULL) infix(root->lchild); printf("%c", root->item); if(root->rchild !=NULL) infix(root->rchild); } void prefix(struct enode* root) { printf("%c", root->item); if(root->lchild != NULL) prefix(root->lchild); if(root->rchild !=NULL) prefix(root->rchild); } void postfix(struct enode* root) { if(root->lchild != NULL) postfix(root->lchild); if(root->rchild !=NULL) postfix(root->rchild); printf("%c", root->item); } struct enode* pop(void) { return(stack[top--]); } void push(struct enode* root) { stack[++top] = root; } Output: Enter equation in the form of postfix: ab+cde+** You have entered: ab+cde+** Select the output form: 1) [i]nfix 2) p[r]efix 3) p[o]stfix

4) e[x]it Enter u r choice: i Inorder representation of output is: a+b*c*d+e Select the output form: 1) [i]nfix 2) p[r]efix 3) p[o]stfix 4) e[x]it Enter u r choice: r Preorder representation of output is: *+ab*c+de Select the output form: 1) [i]nfix 2) p[r]efix 3) p[o]stfix 4) e[x]it Enter u r choice: o Postorder representation of output is: ab+cde+** Select the output form: 1) [i]nfix 2) p[r]efix 3) p[o]stfix 4) e[x]it Enter u r choice:x

ExNo:6 Implement a binary search tree. Aim


To write a C program to implement Binary Search Tree ADT. Algorithm 1.Create a memory space for the Root node and initialize the value to zero. 2.Read the value. 3.If the value is less than the root value,it is assigne das the left child of the root.Else if new value is greater than the root value,it is assigned as the right child of the root. Else if there si no value in the root, the new value is assigned as the root 4. Repeat the step(2) and (3) to insert the n number of values Search Operation: 1. Read the key value to be searched 2. check whether the root is not null 3. if the value to be searched is less than the root, consider the left sub tree for searching the particular element else if the value is greater than the root consider the right sub-tree to search the particular element else if he value is equal then return that is the value which was searched. Insertion: 1. Read the key value to be deleted 2. First perform the search operation to check whether the key values are different from those existing element.

3. If the search is unsuccessful, then the key is inserted at the point the search is terminated. Deletion: 1. Read the key value to be deleted 2. First perform search operation to get the particular key element 3. If it is, check whether a. It is leaf node, b. Or it has only one sub-tree c. Or it has exactly 2 sub-trees. 4. if the key value is the leaf-node, assign null value to that node, else if the key contains only one sub-tree either left (or) right sub-tree, if the key is root, it is discarded and its single sub-tree becomes the new search tree root. Else if the key is the child node, then we change the pointer from the root of key to the child of the key 5. If the key contains both left and right sub-tree replace the key with either largest element in the left sub-tree or smallest in the right sub-tree.

Program:
#include<stdio.h> #include<conio.h> #include<process.h> #include<alloc.h> struct tree { int data; struct tree *lchild; struct tree *rchild; }*t,*temp; int element; void inorder(struct tree *); void preorder(struct tree *); void postorder(struct tree *); struct tree * create(struct tree *, int); struct tree * find(struct tree *, int); struct tree * insert(struct tree *, int); struct tree * del(struct tree *, int); struct tree * findmin(struct tree *); struct tree * findmax(struct tree *); void main() { int ch; do { printf("\n\t\t\tBINARY SEARCH TREE"); printf("\n\t\t\t****** ****** ****"); printf("\nMain Menu\n"); printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");

printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n"); printf("\nEnter ur choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the data:"); scanf("%d",&element); t=create(t,element); inorder(t); break; case 2: printf("\nEnter the data:"); scanf("%d",&element); t=insert(t,element); inorder(t); break; case 3: printf("\nEnter the data:"); scanf("%d",&element); t=del(t,element); inorder(t); break; case 4: printf("\nEnter the data:"); scanf("%d",&element); temp=find(t,element); if(temp->data==element) printf("\nElement %d is at %d",element,temp); else printf("\nElement is not found"); break; case 5: temp=findmin(t); printf("\nMax element=%d",temp->data); break; case 6: temp=findmax(t); printf("\nMax element=%d",temp->data); break; case 7: inorder(t); break; case 8: preorder(t); break;

case 9: postorder(t); break; case 10: exit(0); } }while(ch<=10); } struct tree * create(struct tree *t, int element) { t=(struct tree *)malloc(sizeof(struct tree)); t->data=element; t->lchild=NULL; t->rchild=NULL; return t; } struct tree * find(struct tree *t, int element) { if(t==NULL) return NULL; if(element<t->data) return(find(t->lchild,element)); else if(element>t->data) return(find(t->rchild,element)); else return t; } struct tree *findmin(struct tree *t) { if(t==NULL) return NULL; else if(t->lchild==NULL) return t; else return(findmin(t->lchild)); } struct tree *findmax(struct tree *t) { if(t!=NULL) { while(t->rchild!=NULL) t=t->rchild; } return t;

} struct tree *insert(struct tree *t,int element) { if(t==NULL) { t=(struct tree *)malloc(sizeof(struct tree)); t->data=element; t->lchild=NULL; t->rchild=NULL; return t; } else { if(element<t->data) { t->lchild=insert(t->lchild,element); } else if(element>t->data) { t->rchild=insert(t->rchild,element); } else if(element==t->data) { printf("element already present\n"); } return t; } } struct tree * del(struct tree *t, int element) { if(t==NULL) printf("element not found\n"); else if(element<t->data) t->lchild=del(t->lchild,element); else if(element>t->data) t->rchild=del(t->rchild,element); else if(t->lchild&&t->rchild) { temp=findmin(t->rchild); t->data=temp->data; t->rchild=del(t->rchild,t->data);

} else { temp=t; if(t->lchild==NULL) t=t->rchild; else if(t->rchild==NULL) t=t->lchild; free(temp); } return t; } void inorder(struct tree *t) { if(t==NULL) return; else { inorder(t->lchild); printf("\t%d",t->data); inorder(t->rchild); } } void preorder(struct tree *t) { if(t==NULL) return; else { printf("\t%d",t->data); preorder(t->lchild); preorder(t->rchild); } } void postorder(struct tree *t) { if(t==NULL) return; else { postorder(t->lchild); postorder(t->rchild); printf("\t%d",t->data); } }

Output: BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :1 Enter the data:10 10 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :2 Enter the data:20 10 20 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit

Enter ur choice :2 Enter the data:30 10 20 30 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :2 Enter the data:25 10 20 25 30 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :4 Enter the data:25 Element 25 is at 2216 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder

9.Postorder 10.Exit Enter ur choice :5 Max element=10 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :6 Max element=30 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :7 10 20 25 30 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder

10.Exit Enter ur choice :8 10 20 30 25 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :9 25 30 20 10 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :3 Enter the data:10 20 25 30 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder

10.Exit Enter ur choice :10

Ex No: 7 Implement Priority Queue using heaps Aim:To write a C program to Implement Priority Queue using heaps Algorithm Insertion
Step1: To insert an element X in to the heap, create a hole in the next available location, otherwise the tree will not be complete. Step2: If X can be placed in the hole without violating heap order, then place the element X there itself. Step3: Otherwise slide the element that is in the holes parent node in the hole, thus bubbling the hole up towards the root. Step4: This process continues until X can be placed in the hole Step5: This general strategy is known as percolate up, in which the new element is percolated up the heap until the correct location is found.

Delete Min
Step1: In binary heap the minimum element is found in the root. Step2; When this minimum is removed, a hole is created at the root. Since the heap becomes one smaller, makes the last element X in the heap to move somewhere in the heap. Step3: If X can be placed in hole without violating heap order property place it. Otherwise slide the smaller of the holes children in to the hole, thus pushing the hole down one level. Step4: Repeat until X can be placed in the hole. This general strategy is known as percolate down.

Program:
#include<iostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> #include<process.h> struct heapnode { int capacity; int size; int *elements; }; int isFull(struct heapnode *h) { if(h->capacity==h->size) return 1; else return 0; } int isEmpty(struct heapnode *h) { if(h->size==0)

return 1; else return 0; } void display(struct heapnode *h) { printf("\nPriority Queue Display :"); if(isEmpty(h)) { printf("\nPriority queue is empty"); return; } else for(int i=1;i<=h->size;i++) printf("%d\t",h->elements[i]); } struct heapnode * initialize() { struct heapnode *t; int maxelements; printf("\nEnter the Size of the Priority queue :"); scanf("%d",&maxelements); if(maxelements<5) { printf("Priority queue size is to small"); getch(); exit(0); } t=(struct heapnode *)malloc(sizeof(struct heapnode *)); if(t==NULL) { printf("out of space!"); getch(); exit(0); } t->elements=(int *)malloc((maxelements+1)*sizeof(int)); if(t->elements==NULL) { printf("Out of space"); getch(); exit(0);

} t->capacity=maxelements; t->size=0; t->elements=0; return t; } void insert(int x,struct heapnode *h) { int i; if(isFull(h)) { printf("Priority queue is full"); return; } for(i=++h->size;h->elements[i/2]>x;i/=2) h->elements[i]=h->elements[i/2]; h->elements[i]=x; } int deleteMin(struct heapnode *h) { int i,child; int MinElement,LastElement; if(isEmpty(h)) { printf("Priority queue is empty"); return 0; } MinElement=h->elements[1]; LastElement=h->elements[h->size--]; for(i=1;i*2<=h->size;i=child) { child=i*2; if(child!=h->size&&h->elements[child+1]<h->elements[child]) child++; if(LastElement>h->elements[child]) h->elements[i]=h->elements[child]; else break; } h->elements[i]=LastElement; return MinElement; }

void main() { int ch,ins,del; struct heapnode *h; clrscr(); printf("\nPriority Queue using Heap"); h=initialize(); while(1) { printf("\n1. Insert\n2. DeleteMin\n3. Display\n4. Exit"); printf("\nEnter u r choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the element:"); scanf("%d",&ins); insert(ins,h); break; case 2: del=deleteMin(h); printf("\nDeleted element is %d",del); getch(); break; case 3: display(h); getch(); break; case 4: exit(0); } } } Output: Priority Queue using Heap Enter the Size of the Priority queue :14 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:10 1. Insert 2. DeleteMin 3. Display 4. Exit

Enter u r choice :1 Enter the element:34 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:24 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:67 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :3 Priority Queue Display :10 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :2 Deleted element is 10 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :2 Deleted element is 24 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :3 Priority Queue Display :34 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :4

34

24

67

67

Ex No:8 Implement Hashing Technique Separate Chaining


Aim: To write a C program to implement separate chaining. Algorithm

Step1:A pointer field is added to each record location. When a new key arrives the linked list is extended . Step2:To insert an element, traverse down the appropriate list to check whether the element is already in place. Step3: If the element turns to be new one it is inserted either at the front of the list or at the end of the list. Step4: If it is a duplicate element , an extra field is kept and placed

Program:
#include <stdio.h> #include <conio.h> #include <stdlib.h> struct listnode { int element; struct listnode *next; }; struct hashtbl { int tablesize; struct listnode **thelists; }; int hash(int key,int tablesize) { return (key%tablesize); } struct hashtbl * initializetable(int tablesze) { struct hashtbl *h; int i; if(tablesze<5) { printf("Table size too small"); return NULL; } h=(struct hashtbl *)malloc(sizeof(struct hashtbl *)); if(h==NULL) { printf("out of space!!!"); getch(); exit(0); } h->tablesize=tablesze; h->thelists=(struct listnode **)malloc(sizeof(struct listnode *)*h->tablesize); if(h->thelists==NULL) {

printf("ouf of space!!!"); getch(); exit(0); } for(i=0;i<h->tablesize;i++) { h->thelists[i]=(struct listnode *)malloc(sizeof(struct listnode *)); if(h->thelists[i]==NULL) { printf("out of space !!!"); getch(); exit(0); } else //h->thelists[i]=NULL; h->thelists[i]->next=NULL; } return h; } void display(struct hashtbl *h) { struct listnode *p,*l; printf("\nDisplay\n"); for(int i=0;i<h->tablesize;i++) { l=h->thelists[i]; p=l->next; printf("%d",i); do { if(p!=NULL) printf("-->\t%d",p->element); else { printf("--> %s","NULL"); break; } p=p->next; }while(1); printf("\n"); } getch(); } struct listnode * find(int key,struct hashtbl *h) { struct listnode *p,*l;

l=h->thelists[hash(key,h->tablesize)]; p=l->next; while(p!=NULL && p->element!=key) p=p->next; return p; } void insert(int key,struct hashtbl *h) { struct listnode *pos,*newcell,*l; pos=find(key,h); if(pos==NULL) { newcell=(struct listnode *)malloc(sizeof(struct listnode *)); if(newcell==NULL) { printf("out of space!!!"); getch(); exit(0); } else { l=h->thelists[hash(key,h->tablesize)]; newcell->next=l->next; newcell->element=key; l->next=newcell; } } } void main() { int ch,ins,found; struct hashtbl *h; struct listnode *p; clrscr(); printf("\nSeparate Chaining using Hash Function"); h=initializetable(10); while(1) { printf("\n1. Insert\n2. Find\n3. Display\n4. Exit"); printf("\nEnter u r choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the element to insert:"); scanf("%d",&ins);

insert(ins,h); break; case 2: printf("\nEnter the element to find:"); scanf("%d",&found); p=find(found,h); if(p==NULL) printf("Element is not found"); else printf("\nThe element %d is found",found); getch(); break; case 3: display(h); getch(); break; case 4: exit(0); } } } Output : Separate Chaining using Hash Function 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :1 Enter the element to insert:10 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :1 Enter the element to insert:20 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :1 Enter the element to insert:34 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :1

Enter the element to insert:56 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :3 Display 0--> 20--> 10--> NULL 1--> NULL 2--> NULL 3--> NULL 4--> 34--> NULL 5--> NULL 6--> 56--> NULL 7--> NULL 8--> NULL 9--> NULL 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :2 Enter the element to find:20 The element 20 is found 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :2 Enter the element to find:100 Element is not found 1. Insert 2. Find 3. Display 4. Exit Enter u r choice :4

Ex No:9 Implement Dijkstra's algorithm using priority queues Aim:


To write a C program to Implement Dijkstra's algorithm using priority queues

Algorithm
1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for all other nodes. 2. Mark all nodes as unvisited. Set initial node as current. 3. For current node, consider all its unvisited neighbors and calculate their distance (from the initial node). For example, if current node (A) has distance of 6, and an edge

connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the previously recorded distance (infinity in the beginning, zero for the initial node), overwrite the distance. 4. When we are done considering all neighbors of the current node, mark it as visited. A visited node will not be checked ever again; its distance recorded now is final and minimal. 5. Set the unvisited node with the smallest distance (from the initial node) as the next "current node" and continue from step 3 .

Program:
#include< stdio.h> #include< conio.h> #include< process.h> #include< string.h> #include< math.h> #define IN 99 #define N 6 int dijkstra(int cost[][N], int source, int target); void main() { int cost[N][N],i,j,w,ch,co; int source, target,x,y; clrscr(); printf("\tShortest Path Algorithm(DIJKSRTRA's ALGORITHM\n\n"); for(i=1;i< N;i++) for(j=1;j< N;j++) cost[i][j] = IN; for(x=1;x< N;x++) { for(y=x+1;y< N;y++) { printf("Enter the weight of the path between node %d and %d: ",x,y); scanf("%d",&w); cost [x][y] = cost[y][x] = w; } printf("\n"); } printf("\nEnter The Source:"); scanf("%d", &source); printf("\nEnter The target"); scanf("%d", &target); co = dijsktra(cost,source,target); printf("\nShortest Path: %d",co); getch(); } int dijsktra(int cost[][N],int source,int target) {

int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j; char path[N]; for(i=1;i< N;i++) { dist[i] = IN; prev[i] = -1; } start = source; selected[start]=1; dist[start] = 0; while(selected[target] ==0) { min = IN; m = 0; for(i=1;i< N;i++) { d = dist[start] +cost[start][i]; if(d< dist[i]&&selected[i]==0) { dist[i] = d; prev[i] = start; } if(min>dist[i] && selected[i]==0) { min = dist[i]; m = i; } } start = m; selected[start] = 1; } start = target; j = 0; while(start != -1) { path[j++] = start+65; start = prev[start]; } path[j]='\0'; strrev(path); printf("%s", path); return dist[target]; }

Output
Shortest Path Algorithm(DIJKSRTRA's ALGORITHM Enter the weight of the path between node 1 and 2: 2

Enter the weight of the path between node 1 and 3: 3 Enter the weight of the path between node 1 and 4: 4 Enter the weight of the path between node 1 and 5: 5 Enter the weight of the path between node 2 and 3: 5 Enter the weight of the path between node 2 and 4: 2 Enter the weight of the path between node 2 and 5: 3 Enter the weight of the path between node 3 and 4: 1 Enter the weight of the path between node 3 and 5: 4 Enter the weight of the path between node 4 and 5: 5 Enter The Source:2 Enter The target4 CE Shortest Path: 2

Ex No:10 Implement Knapsack Problem Aim: To write a C program to implement Knapsack Problem .
Algorithm Step1:Get the number of Objects. Step2: Get the maximum capacity of Knapsack Step3: Enter the weights and values of Objects. Step4:Fill the knapsack with maximum profit earned. But it should not exceed the capacity of the knapsack. Upper Bound=v+(W-w)(vi+1/w i+1) v-total value of items W-knapsack capacity w-total weight of items Step5:Repeat the steps until the maximum profit is earned. Program: #include<stdio.h> #include<conio.h> int c,c1,n,i,j,k; int q[10],X[10][10],W[10],P[10],max; void get(); void knapsack(); void display(); void get() { printf("\nEnter the no.of objects:"); scanf("%d",&n); printf("\nEnter the size of the knapsack:"); scanf("%d",&c); printf("\nEnter the weight and profit of objects:\n"); for(i=1;i<=n;i++) { printf("\nEnter the weight %d:\t",i); scanf("%d",&W[i]); printf("\nEnter the profit of weight:");

scanf("%d",&P[i]); } } void knapsack() { for(j=1;j<=n;j++) { for(i=1;i<=n;i++) { X[j][i]=0; q[j]=0; } c1=c; for(i=j;i<=n&&W[i]<=c1;i++) { X[j][i]=1; c1=c1-W[i]; q[j]=q[j]+X[j][i]*P[i]; } } max=q[i]; for(i=1l;i<=n;i++) { if(q[i]>max) { max=q[i]; k=i; } } } void display() { printf("\nThe optimal solution \tprofit\n"); for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=n;j++) { printf("%d\t",X[i][j]); } printf("%d\t",q[i]); } printf("\nThe maximum profit is %d",max); } void main() {

clrscr(); get(); knapsack(); display(); getch(); } Output: Enter the no.of objects:4 Enter the size of the knapsack:12 Enter the weight and profit of objects: Enter the weight 1: 6 Enter the profit of weight:50 Enter the weight 2: 3 Enter the profit of weight:26 Enter the weight 3: 9 Enter the profit of weight:84 Enter the weight 4: 4 Enter the profit of weight:12 The optimal solution profit 1 1 0 0 76 0 1 1 0 110 0 0 1 0 84 0 0 0 1 12 The maximum profit is 110

You might also like