Вы находитесь на странице: 1из 47

/*1.

PROGRAM FOR IMPLEMENTATION OF SINGLE LINKED LIST */ Aim: To implement the Singly Linked List program using C language. Algorithm: 1. Open tc, open new file and save it as list.c 2. Declare a structure containing data part and a link part. 3. *p is a global pointer of structure node that contains the address of the first node in list. 4. Define the functions delnode, append, addbeg, addafter, display, count, reverse. 5. The delnode function deletes a node. 6. The append function adds a node at the last of the list. 7. The addbeg function adds the new node at the beginning of the list. 8. The addafter function adds the new node after the specified number of nodes. 9. The count function counts the total number of nodes. 10. The reverse function the list. 11. Call these functions in main function. 12. End of the program.

Program: #include<stdio.h> //#define NULL 0 /* STRUCTURE CONTANING A DATA PART AND A LINK PART */ struct node { int data; struct node *next; }*p; /* P IS A GLOBAL POINTER CONTAINS THE ADRESS OF THE FIRST NODE IN LIST*/ /*THIS FUNCTION DELETES A NODE */ delnode(int num) { struct node *temp, *m; temp=p; while(temp!=NULL) { if(temp->data==num) { if(temp==p) { p=temp->next; free(temp); return; } else { m->next=temp->next; free(temp); return; } }else { m=temp; temp= temp->next; } } printf(" ELEMENT %d NOT FOUND ", num); }

/*THIS FUNCTION ADDS A NODE AT THE LAST OF LINKED LIST */ append( int num ) { struct node *temp,*r; /* CREATING A NODE AND ASSIGNING A VALUE TO IT */ temp= (struct node *)malloc(sizeof(struct node)); temp->data=num; r=(struct node *)p; if (p == NULL) /* IF LIST IS EMPTY CREATE FIRST NODE */ { p=temp; p->next =NULL; } else { /* GO TO LAST AND ADD*/ while( r->next != NULL) r=r->next; r->next =temp; r=temp; r->next=NULL; } } /* ADD A NEW NODE AT BEGINNING */ addbeg( int num ) { /* CREATING A NODE AND INSERTING VALUE TO IT */ struct node *temp; temp=(struct node *)malloc(sizeof(struct node)); temp->data=num; /* IF LIST IS NULL ADD AT BEGINNING */ if ( p== NULL) { p=temp; p->next=NULL; } else { temp->next=p; p=temp; } } 3

/* ADD A NEW NODE AFTER A SPECIFIED NO OF NODES */ addafter(int num, int loc) { int i; struct node *temp,*t,*r; r=p; /* here r stores the first location */ if(loc > count()+1 || loc <= 0) { printf("insertion is not possible : "); return; } if (loc == 1)/* if list is null then add at beginning */ { addbeg(num); return; } else { for(i=1;i<loc;i++) { t=r; /* t will be holding previous value */ r=r->next; } temp=(struct node *)malloc(sizeof(struct node)); temp->data=num; t->next=temp; t=temp; t->next=r; return; } } /* THIS FUNCTION DISPLAYS THE CONTENTS OF THE LINKED LIST */ display(struct node *r) { r=p; if(r==NULL) { printf("NO ELEMENT IN THE LIST :"); return; } /* traverse the entire linked list */ while(r!=NULL) { printf(" -> %d ",r->data); r=r->next; } printf(" "); } 4

/*THIS FUNCTION COUNTS THE NUMBER OF ELEMENTS IN THE LIST*/ count() { struct node *n; int c=0; n=p; while(n!=NULL) { n=n->next; c++; } return(c); } /*THIS FUNCTION REVERSES A LINKED LIST*/ reverse(struct node *q) { struct node *m, *n,*l,*s; m=q; n=NULL; while(m!=NULL) { s=n; n=m; m=m->next; n->next=s; } p=n; } /* THIS IS THE MAIN PROGRAM */ main() { int i; p=NULL; while(1) /* this is an indefinite loop */ { printf("1.INSERT A NUMBER AT BEGINNING;"); printf(" 2.INSERT A NUMBER AT LAST:"); printf(" 3.INSERT A NUMBER AT A PARTICULAR LOCATION INlIST:"); printf(" 4.PRINT THE ELEMENTS IN THE LIST :"); printf(" 5.PRINT THE NUMBER OF ELEMENTS IN THE LIST"); printf(" 6.DELETE A NODE IN THE LINKED LIST:"); printf(" 7.REVERSE A LINKED LIST :"); printf(" 8.GET OUT OF LINKED LIST (BYEE BYEE):"); printf(" PLEASE, ENTER THE NUMBER:"); scanf("%d",&i); /* ENTER A VALUE FOR SWITCH */

switch(i) { case 1: { int num; printf(" PLEASE ENTER THE NUMBER :-"); scanf("%d",&num); addbeg(num); break; } case 2: { int num; printf(" PLEASE ENTER THE NUMBER :-"); scanf("%d",&num); append(num); break; } case 3: { int num, loc,k; printf(" PLEASE ENTER THE NUMBER :-"); scanf("%d",&num); printf("PLEASE ENTER THE LOCATION NUMBER :-"); scanf("%d",&loc); addafter(num,loc); break; } case 4: { struct node *n; printf("THE ELEMENTS IN THE LIST ARE :"); display(n); break; } case 5: { struct node *n; display(n); printf(" TOTAL NO OF ELEMENTS IN THE LSIT ARE %d",count()); break; } case 6: { int num; printf(" PLEASE ENTER A NUMBER FROM THE LIST :"); scanf("%d",&num); delnode(num); break; } 6

case 7: { reverse(p); display(p); break; } case 8: { exit(); } }/* end if switch */ }/* end of while */ }/* end of main */

OUTPUT: 1. INSERT A NUMBER AT BEGINNING; 2. INSERT A NUMBER AT LAST: 3. INSERT A NUMBER AT A PARTICULAR LOCATION INLIST: 4. PRINT THE ELEMENTS IN THE LIST: 5. PRINT THE NUMBER OF ELEMENTS IN THE LIST 6. DELETE A NODE IN THE LINKED LIST: 7. REVERSE A LINKED LIST: 8. GET OUT OF LINKED LIST (BYEE BYEE): PLEASE, ENTER THE NUMBER: 1 PLEASE ENTER THE NUMBER:-5 PLEASE, ENTER THE NUMBER: 1 PLEASE ENTER THE NUMBER:-6 PLEASE, ENTER THE NUMBER: 4 THE ELEMENTS IN THE LIST ARE: -> 6 -> PLEASE, ENTER THE NUMBER: 5 -> 6 -> 5 TOTAL NO OF ELEMENTS IN THE LSIT ARE 2 PLEASE, ENTER THE NUMBER: 4 THE ELEMENTS IN THE LIST ARE: -> 6 PLEASE, ENTER THE NUMBER: 8

Result: Thus the program has been implemented using C language and verified.

/* 2. PROGRAM FOR IMPLEMENTATION OF SINGLE LINKED LIST */ Aim: To implement the polynomial addition using linked list program using C language. Algorithm: 1. Start the program. 2. Declare a structure link containing coeff, pow,*next. 3. Define the functions create, show, polyadd. 4. Allocate the memory to three variables poly1, poly2 and poly. 5. Get the coefficients of poly1 and poly2. 6. The sum of the two polynomials are added and displayed in poly. 7. Stop the program.

Program: #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;

10

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:");

11

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'); }

12

OUTPUT: Enter 1st number: Enter coeff:2 Enter power:2 continue(y/n): enter coeff:6 enter power:1 continue(y/n): enter coeff:3 enter power:0 continue(y/n): enter 2nd number: enter coeff:5 enter power:2 continue(y/n): enter coeff:4 enter power:1 continue(y/n): enter coeff:8 enter power:0 continue(y/n): 1st Number:2x^2+6x^1+3x^0 2nd Number:5x^2+4x^1+8x^0 Added polynomial:7x^2+10x^1+11x^0 add two more numbers:

Result: Thus the program has been implemented using C language and verified.

13

/*3. LINKED LIST IMPLEMENTATIONS OF STACK ADT*/ Aim: To write a program to implement a stack ADT using linked list Algorithm: 1. Declare the array and variable 2. Using malloc() function to allocate the memory for the nodes 3. Create a PUSH function to insert an element into the stack and POP function to delete an element from the stack 4. Check the overflow and underflow condition 5. After performing a POP operation using free() function memory for that node is released 6. Check the result 7. Stop the program

14

Program: #include<stdio.h> #include<conio.h> #include<alloc.h> struct node { int info; struct node *link; }*top=NULL,*p,*temp,*disp; int no; void main() { int c; clrscr(); do { printf("ENTER 1-PUSH,2-POP,3-DISPLAY,4-EXIT \n"); printf("ENTER THE CHOICE \n"); scanf("%d",&c); switch(c) { case 1: { push(); break; } case 2: { pop(); break; } case 3: { display(); break; } } } while(c<4); getch(); } push() { p=(struct node*)malloc(sizeof(struct node)); printf("ENTER THE NUMBER TO BE INSERTED \n");

15

scanf("%d",&no); p->info=no; if(top==NULL) { top=p; p->link=NULL; temp=p; } else { p->link=top; top=p; } return; } pop() { if(top==NULL) printf("STACK IS EMPTY \n"); else { temp=top; top=top->link; free(temp); printf("THE DELETED ITEM IS %d\n",temp->info); } return; } display() { if(top==NULL) printf("STACK IS EMPTY \n"); else { printf("THE ELEMENTS IN THE STACK ARE :\n"); for(disp=top;disp!=NULL;disp=disp->link) printf("%d\n",disp->info); } return; }

16

Output: ENTER 1,PUSH,2-POP,3-DISPLAY,4-EXIT ENTER THE CHOICE 1 ENTER THE NUMBER TO BE INSERTED 3 ENTER 1,PUSH,2-POP,3-DISPLAY,4-EXIT ENTER THE CHOICE 1 ENTER THE NUMBER TO BE INSERTED 4 ENTER 1,PUSH,2-POP,3-DISPLAY,4-EXIT ENTER THE CHOICE 3 THE ELEMENTS IN THE STACK ARE 3 4 ENTER 1,PUSH,2-POP,3-DISPLAY,4-EXIT ENTER THE CHOICE 4

Result: Thus the program has been implemented using C language and verified.

17

/* 4. PROGRAM FOR IMPLEMENTATION OF CIRCULAR QUEUE USING ARRAY */

Aim: To implement the circular queue program based on array using C language. Algorithm: 1. Start the program. 2. Define the MaxSize value as 5. 3. Declare the functions queuein, queueout and disp functions. 4. Enter the values to queuein function and increment the tail value by 1. 5. To delete the values call the queueout function and increment the head value by 1. 6. Call the disp function to display the contents of the queue. 7. Stop the program.

18

Program: #include <stdio.h> #define MaxSize 5 /* size queue size */ int queue[MaxSize]; int head=0, /* head indicator */ tail=0; /* tail indicator */ int queuein(int); int queueout(int *); void disp(void); void main(void) { int c,n; clrscr(); while (printf("]"),(c=getchar())!=EOF){ rewind(stdin); if (c=='i' || c=='I'){ printf("data--> "); scanf("%d",&n);rewind(stdin); if (queuein(n)==-1){ printf("Full\n"); } } if (c=='o' || c=='O'){ if (queueout(&n)==-1) printf("Empty\n"); else printf("queue data --> %d\n",n); } if (c=='L' || c=='l'){ disp(); } } } int queuein(int n) /* insert to queue*/ { if ((tail+1)%MaxSize !=head){

19

queue[tail]=n; tail++; tail=tail%MaxSize; return 0; } else return -1; } int queueout(int *n) /* rmove data from queue */ { if (tail!=head){ *n=queue[head]; head++; head=head%MaxSize; return 0; } else return -1; /* queue is empty */ } void disp() /* display content of queue*/ { int i;//b; // for(i=0;i<queue[MaxSize];i++) // printf("%d",queue[MaxSize]); // } i=head; while (i!=tail){ printf("%d\n",queue[i]); i++; i=i%MaxSize; } } /* queue is full */

20

Output: ]i data--> 5 ]i data--> 6 ]i data--> 2 ]o queue data --> 5 ]o queue data --> 6 ]o queue data --> 2 ]o Empty ]l 562]

Result: Thus the program has been implemented using C language and verified.

21

/*5. BINARY TREE TRAVERSAL*/ Aim To write a C program to perform the Binary tree traversal operations using linked list Algorithm: Step 1: Start the program. Step 2: Initialize pointer root to zero. Step 3: If the create option is selected, then create the Binary Search Tree by entering all the elements once. Step 4: If the insert option is selected, then enter the element to be inserted. If the same element is found, do not enter the insert element. If not found, enter the key in Binary Search Tree. Step 5: If the preorder option is selected, then display in preorder ie., print the data in root and then traverse through the left subtree and then thro' the right subtree. Step 6: If the inorder option is selected, then display in inorder ie., first go to the left subtree, print the data in the previous node and then go to the right subtree. Step 7: If the postorder option is selected, then display in postorder ie., first go to the left subtree and then go to right subtree and then print the data in the node. Step 8: Stop the program.

22

Program: #include<stdio.h> #include<alloc.h> #define TRUE 1 struct node{ int info; struct node *left; struct node *right; }; typedef struct node *nodeptr; nodeptr p; void main () { nodeptr proot,q; int number ,choice; nodeptr maketree(int); nodeptr getnode(void); printf("enter a number (at end imput -1):"); scanf("%d",&number); if(number==-1) exit(1); proot=maketree(number); p=proot; while(TRUE) { printf("enter next number:"); scanf("%d",&number); if(number == -1) break; p=proot; q=proot; while(number != p->info && q!=NULL) { p=q; if(number<p->info) q=p->left; else q=p->right; } if (number<p->info) setleft(p,number); else setright(p,number); } printf("\nenter your coice:preorder(1),inorder(2),postorder(3),end(4)");

23

while(TRUE) { printf("\n enter ur choice:"); scanf("%d",&choice); switch(choice) { case 1: preorder(proot); break; case 2: inorder(proot); break; case 3 : postorder(proot); break; case 4: exit(2); } } } /* end of main*/ nodeptr getnode() { nodeptr; r=(nodeptr) malloc(sizeof(struct node)); return r; } nodeptr maketree(x) int x; { nodeptr r; r=getnode(); if(r == NULL) exit(1); r->info = x; r->left = NULL; r->right = NULL; return(r); } setleft(r,x) nodeptr r; int x ; { if (r==NULL) printf("\n void insertion "); else if(r->left !=NULL) printf("\n invalid insertion "); else { r->left = maketree(x);

24

}; setright(r,x) { nodeptr r; int x; if(r==NULL) printf ("\n void insertion "); else if (r->right != NULL) printf ("\n invalid insertion "); else { r->right =maketree(x); } } preorder(r) nodeptr r; { if( r != NULL) { printf("%d",r->info); preorder(r->left); preorder(r->right); } } inorder(r) { nodeptr r; if(r != NULL) { inorder(r->left); printf("%d",r->info); inorder(r->right); } } postorder(r) nodeptr r; { if(r != NULL) { postorder(r->left); postorder(r->right); printf("%d",r->info); } }}

25

Output: enter a number (at end imput -1): 5 enter next number: 8 enter next number: 1 enter next number: 9 enter next number: -1 enter your coice:preorder(1),inorder(2),postorder(3),end(4) 2 1 5 8 9 enter your coice:preorder(1),inorder(2),postorder(3),end(4) 4

Result: Thus the program has been implemented using C language and verified.

26

/*6. PROGRAM FOR IMPLEMENTATION OF BINARY SEARCH TREE*/ Aim: To implement the Binary search tree program using C language. Algorithm:

1. Start the program. 2. Declare the structure BT containing data value, left and right pointers. 3. Define the functions insert,search,inorder,preorder,postorder. 4. Call the functions in the main function. 5. Enter the number of nodes and values of nodes. 6. Select the appropriate choice to do the traversal. 7. Stop the program.

27

Program: #include<stdio.h> struct BT { int data; struct BT *right,*left; }; void insert(struct BT ** ptr,int d) { if((*ptr)==NULL) { (*ptr)=(struct BT*)malloc(sizeof(struct BT)); (*ptr)->data=d; (*ptr)->left=(*ptr)->right=NULL; } else { if((*ptr)->data>d) insert(&((*ptr)->left),d); else insert(&((*ptr)->right),d); } return; } int search(struct BT *ptr,int no) { if(ptr==NULL) return(0); if(ptr->data==no) return(1); if(ptr->data>no) return(search(ptr->left,no)); else return(search(ptr->right,no)); } void inorder(struct BT *ptr) { if(ptr==NULL) return; else {

28

inorder(ptr->left); printf("\t%d",ptr->data); inorder(ptr->right); } } void preorder(struct BT*ptr) { if(ptr==NULL) return; else { printf("\t%d",ptr->data); preorder(ptr->left); preorder(ptr->right); } } void postorder(struct BT*ptr) { if(ptr==NULL) return; else { postorder(ptr->left); postorder(ptr->right); printf("\t%d",ptr->data); } } main() { struct BT*root; int ch,d,no,f; root=NULL; while(ch!=6) { printf("\n 1.Insert\n 2.Search\n 3.Inorder\n 4.Preorder\n 5.Postorder\n 6.Exit\n"); printf("\n Enter the choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the data:"); scanf("%d",&d); insert(&root,d); break; case 2: printf("Enter the node:");

29

scanf("%d",&no); f=search(root,no); if(f==0) printf("Node is not present"); else printf("Node is present"); break; case 3: inorder(root); break; case 4: preorder(root); break; case 5: postorder(root); break; case 6: break; } } }

30

OUTPUT: 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:1 Enter the data:5 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:1 Enter the data:8 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:1 Enter the data:1 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:3 1 5 8 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder

31

6.Exit Enter the choice:4 5 1 8 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:5 1 8 5 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:2 Enter the node:7 Node is not present 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice:2 Enter the node:8 Node is present 1.Insert 2.Search 3.Inorder 4.Preorder 5.Postorder 6.Exit Enter the choice: 6 Result: Thus the program has been implemented using C language and verified.

32

/* 8. PROGRAM FOR IMPLEMENTATION OF HASHING TECHNIQUES*/ Aim: To implement the hashing techniques program using C language. Algorithm: 1. Start the program. 2. Declare the array size of the hash table. 3. Declare the functions insert, search, delete, display. 4. Call these functions in the main function 5. Enter the choice to do the operation. 6. Stop the program.

33

Program: #include<stdio.h> int ar[10],i,g=0,key; void insert(); void search(); void delete(); void display(); main() { int ch; for(i=0;i<10;i++) //to initialise every element as '-1' ar[i]=-1; do { p1: printf("\n\t\t\t\t\tMENU \n1.Insert \n2.Search \n3.Delete \n4.Display \n5.Exit"); scanf("%d",&ch); switch(ch) { case 1: insert(); break; case 2: search(); break; case 3: delete(); break; case 4: display(); break; case 5: break; default:printf("\nInvalid choice entry!!!\n"); goto p1; break; } }while(ch!=5); } void insert() { int item,f=0; printf("\nEnter the element to be inserted : "); scanf("%d",&item); key=(item%10)-1; if(ar[key]==-1) { 34

ar[key]=item; f=1; } else { if(key<9) { for(i=key+1;i<10;i++) { if(ar[i]==-1) { f=1; ar[i]=item; break; } } } if(f==0) { for(i=0;i<key;i++) { if(ar[i]==-1) { f=1; ar[i]=item; break; } } } } if(f==0) printf("\nHashTable is Full\n"); } void display() { for(i=0;i<10;i++) if(ar[i]!=-1) { g=1; break; } if(g==1) { for(i=0;i<10;i++) { 35

if(ar[i]==-1) printf("\n---"); else printf("\n%d",ar[i]); } } else printf("\nThe HashTable is empty !!!"); printf("\n"); } void search() { int item,f=0; g=0; printf("\nEnter the element to be searched :: "); scanf("%d",&item); key=(item%10)-1; for(i=0;i<10;i++) { if(ar[i]!=-1) { g=1; break; } } if(g==1) { if(ar[key]==item) { f=1; } else { if(key<9) { for(i=key+1;i<10;i++) { if(ar[i]==item) { f=1; key=i; break; } } } if(f==0) 36

{ for(i=0;i<key;i++) { if(ar[i]==item) { f=1; key=i; break; } } } } if(f==1) printf("\nThe item searched was found in the hash table at position %d !",key+1); else { key=-1; printf("\nThe item searched was not found in the hash table"); } } else printf("\nHashTable is empty!!\n"); } void delete() { search(); if(g!=0) { if(key!=-1) { printf("\nThe element deleted is %d ",ar[key]); ar[key]=-1; } } }

37

Output: MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit

Enter the element to be inserted : 5 MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit

Enter the element to be inserted : 6 MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit

Enter the element to be inserted : 8 MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit4 --------5 6 --8 ----38

MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit 3 Enter the element to be searched :: 8 The item searched was found in the hash table at position 8 ! The element deleted is 8 MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit 4 --------5 6 --------1.Insert 2.Search 3.Delete 4.Display 5.Exit

MENU

Enter the element to be searched :: 1 The item searched was not found in the hash table MENU 1.Insert 2.Search 3.Delete 4.Display 5.Exit 5 Result: Thus the program has been implemented using C language and verified.

39

/* 9. PROGRAM FOR IMPLEMENTATION OF DIJKSTRAS ALGORITHM */ Aim: To implement the Dijkstras algorithm program using C language. Algorithm: 1. Start the program. 2. Define the graph size, max and infinity value. 3. Define the printD and dijikstra functions. 4. Create a file dist.txt and save the number of nodes, u, v, w values. 5. fopen the file dist.txt and pass the values of u,v,w. 6. Call the dijkstra function. 7. Stop the program.

40

Program: #include <stdio.h> #define GRAPHSIZE 2048 #define INFINITY GRAPHSIZE*GRAPHSIZE #define MAX(a, b) ((a > b) ? (a) : (b)) int e; /* The number of nonzero edges in the graph */ int n; /* The number of nodes in the graph */ long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */ long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */ void printD() { int i; for (i = 1; i <= n; ++i) printf("%10d", i); printf("\n"); for (i = 1; i <= n; ++i) { printf("%10ld", d[i]); } printf("\n"); } void dijkstra(int s) { int i, k, mini; int visited[GRAPHSIZE]; for (i = 1; i <= n; ++i) { d[i] = INFINITY; visited[i] = 0; /* the i-th element has not yet been visited */ } d[s] = 0; for (k = 1; k <= n; ++k) { mini = -1; for (i = 1; i <= n; ++i) if (!visited[i] && ((mini == -1) || (d[i] < d[mini]))) mini = i; visited[mini] = 1; for (i = 1; i <= n; ++i) if (dist[mini][i]) 41

if (d[mini] + dist[mini][i] < d[i]) d[i] = d[mini] + dist[mini][i]; } } int main(int argc, char *argv[]) { int i, j; int u, v, w; FILE *fin = fopen("dist.txt", "r"); fscanf(fin, "%d", &e); for (i = 0; i < e; ++i) for (j = 0; j < e; ++j) dist[i][j] = 0; n = -1; for (i = 0; i < e; ++i) { fscanf(fin, "%d%d%d", &u, &v, &w); dist[u][v] = w; n = MAX(u, MAX(v, n)); } fclose(fin); dijkstra(1); printD(); return 0; }

42

Input: dist.txt 10 1 2 10 145 231 243 356 422 439 452 517 534 Output: C:\TC\BIN> 1 2 0 7 1 2 0 7 3 8 3 8 4 5 4 5 5 7 5 7

Result: Thus the program has been implemented using C language and verified.

43

/* 10. PROGRAM FOR IMPLEMENTATION OF KNAPSACK */ Aim: To implement the Knapsack problem using C language. Algorithm: 1. Start the program. 2. Define the MaxWeight. 3. Define the fill_sack function. 4. Add the weight, cost and object values. 5. Pass the input values of c, n, v, w. 6. Stop the program.

44

Program: #include <stdio.h> #define MAXWEIGHT 100 int n = 3; /* The number of objects */ int c[10] = {8, 6, 4}; /* c[i] is the *COST* of the ith object; i.e. what YOU PAY to take the object */ int v[10] = {16, 10, 7}; /* v[i] is the *VALUE* of the ith object; i.e. what YOU GET for taking the object */ int W = 10; /* The maximum weight you can take */ void fill_sack() { int a[MAXWEIGHT]; /* a[i] holds the maximum value that can be obtained using at most i weight */ int last_added[MAXWEIGHT]; /* I use this to calculate which object were added */ int i, j; int aux; for (i = 0; i <= W; ++i) { a[i] = 0; last_added[i] = -1; } a[0] = 0; for (i = 1; i <= W; ++i) for (j = 0; j < n; ++j) if ((c[j] <= i) && (a[i] < a[i - c[j]] + v[j])) { a[i] = a[i - c[j]] + v[j]; last_added[i] = j; } for (i = 0; i <= W; ++i) if (last_added[i] != -1) printf("Weight %d; Benefit: %d; To reach this weight I added object %d (%d$ %dKg) to weight %d.\n", i, a[i], last_added[i] + 1, v[last_added[i]],c[last_added[i]], i - c[last_added[i]]); else printf("Weight %d; Benefit: 0; Can't reach this exact weight.\n", i); printf("---\n"); aux = W; while ((aux > 0) && (last_added[aux] != -1)) {

45

printf("Added object %d (%d$ %dKg). Space left: %d\n", last_added[aux] + 1, v[last_added[aux]], c[last_added[aux]], aux - c[last_added[aux]]); aux -= c[last_added[aux]]; } printf("Total value added: %d$\n", a[W]); } int main(int argc, char *argv[]) { clrscr(); fill_sack(); return 0; }

46

Input: for this input: n=3 c = {8, 6, 4} v = {16, 10, 7} W = 10 Output: Weight 0; Benefit: 0; Can't reach this exact weight. Weight 1; Benefit: 0; Can't reach this exact weight. Weight 2; Benefit: 0; Can't reach this exact weight. Weight 3; Benefit: 0; Can't reach this exact weight. Weight 4; Benefit: 7; To reach this weight I added object 3 (7$ 4Kg) to weight 0 . Weight 5; Benefit: 7; To reach this weight I added object 3 (7$ 4Kg) to weight 1 . Weight 6; Benefit: 10; To reach this weight I added object 2 (10$ 6Kg) to weight 0. Weight 7; Benefit: 10; To reach this weight I added object 2 (10$ 6Kg) to weight 1. Weight 8; Benefit: 16; To reach this weight I added object 1 (16$ 8Kg) to weight 0. Weight 9; Benefit: 16; To reach this weight I added object 1 (16$ 8Kg) to weight 1. Weight 10; Benefit: 17; To reach this weight I added object 2 (10$ 6Kg) to weigh t 4. --Added object 2 (10$ 6Kg). Space left: 4 Added object 3 (7$ 4Kg). Space left: 0 Total value added: 17$

Result: Thus the program has been implemented using C language and verified.

47

Вам также может понравиться