0% found this document useful (0 votes)
187 views

Data Structure and Algorithm Lab Manual

The document describes programs to implement singly and doubly linked lists in C. It includes algorithms and programs for adding, deleting, displaying, counting, and searching nodes in singly and doubly linked lists. It also describes an algorithm and program for representing polynomials as linked lists and adding two polynomials by adding coefficients of the same powers.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
187 views

Data Structure and Algorithm Lab Manual

The document describes programs to implement singly and doubly linked lists in C. It includes algorithms and programs for adding, deleting, displaying, counting, and searching nodes in singly and doubly linked lists. It also describes an algorithm and program for representing polynomials as linked lists and adding two polynomials by adding coefficients of the same powers.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

1. Implement singly and doubly linked lists.

SINGLY LINKED LIST AIM:To write a C program to create a singly linked list implementation. ALGORITHM:1. Start the program. 2. Get the choice from the user. 3. If the choice is to add records, get the data from the user and add them to the list. 4. If the choice is to delete records, get the data to be deleted and delete it from the list. 5. If the choice is to display number of records, count the items in the list and display. 6. If the choice is to search for an item, get the item to be searched and respond yes if the item is found, otherwise no. 7. Terminate the program

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

PROGRAM:#include<stdio.h> #include<conio.h> #include<alloc.h> #define NULL 0 struct info { int data; struct info *next; }; struct info *head,*temp,*disp; void additem(); void delitem(); void display(); int size(); void search(); void main() { int choice; clrscr(); while(1) { printf("\n1.Add records"); printf("\n2.Delete records"); printf("\n3.Display records"); printf("\n4.Count no. of items in the list"); printf("\n5.Searching an item in the list"); printf("\n6.Exit"); printf("\nEnter your choice:"); scanf("%d",&choice); fflush(stdin); switch(choice) { case 1: additem(); break; case 2: delitem(); break; case 3: display(); break; case 4: printf("\nThe size of the list is %d",size()); break;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

case 5: search(); break; case 6: exit(0); } } } void additem() { struct info *add; char proceed='y'; while(toupper(proceed)=='Y') { add=(struct info*)malloc(sizeof(struct info)); printf("Enter data:"); scanf("%d",&add->data); fflush(stdin); if(head==NULL) { head=add; add->next=NULL; temp=add; } else { temp->next=add; add->next=NULL; temp=add; } printf("\nWant to proceed y/n"); proceed=getchar(); fflush(stdin); } } void delitem() { struct info *curr,*prev; int tdata; if(head==NULL) { printf("\nNo records to delete"); return; } printf("\nEnter the data to delete"); scanf("%d",&tdata);

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

fflush(stdin); prev=curr=head; while((curr!=NULL)&&(curr->data!=tdata)) { prev=curr; curr=curr->next; } if(curr==NULL) { printf("\nData not found"); return; } if(curr==head) head=head->next; else { /*for inbetween element deletion*/ prev->next=curr->next; /*for the last element deletion*/ if(curr->next==NULL) temp=prev; } free(curr); } void display() { if(head==NULL) { printf("\nNo data to display"); return; } for(disp=head;disp!=NULL;disp=disp->next) { printf("Data->%d",disp->data); } } int size() { int count=0; if(head==NULL) return count; for(disp=head;disp!=NULL;disp=disp->next) count++; return count; } void search()

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

{ int titem,found=0; if(head==NULL) { printf("\nNo data in the list"); return; } printf("\Enter the no. to search:"); scanf("%d",&titem); for(disp=head;disp!=NULL&&found==0;disp=disp->next) { if(disp->data==titem) found=1; } if(found==0) printf("\nSearch no. is not present in the list"); else printf("\nSearch no. is present in the list"); return; } OUTPUT:1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:1 Enter data:12 Want to proceed y/ny Enter data:13 Want to proceed y/ny Enter data:41 Want to proceed y/nn 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:3 Data->12Data->13Data->41 1.Add records

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:4 The size of the list is 3 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:2 Enter the data to delete13 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:3 Data->12Data->41 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:5 Enter the no. to search:13 Search no. is not present in the list 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:6 RESULT:The given program is implemented, executed, tested and verified successfully.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

DOUBLY LINKED LIST AIM:To write a C program to create a Doubly linked list implementation. ALGORITHM:1. Start the program. 2. Get the choice from the user. 3. If the choice is to add records, get the data from the user and add them to the list. 4. If the choice is to delete records, get the data to be deleted and delete it from the list. 5. If the choice is to display number of records, count the items in the list and display. 6. If the choice is to search for an item, get the item to be searched and respond yes if the item is found, otherwise no. 7. Terminate the program

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

PROGRAM:#include<stdio.h> #include<conio.h> #include<alloc.h> #define NULL 0 struct info { int data; struct info *next; struct info *prev; }; struct info *head,*temp,*disp; void additem(); void delitem(); void display(); int size(); void search(); void main() { int choice; clrscr(); while(1) { printf("\n1.Add records"); printf("\n2.Delete records"); printf("\n3.Display records"); printf("\n4.Count no. of items in the list"); printf("\n5.Searching an item in the list"); printf("\n6.Exit"); printf("\nEnter your choice:"); scanf("%d",&choice); fflush(stdin); switch(choice) { case 1: additem(); break; case 2: delitem(); break; case 3: display(); break; case 4: printf("\nThe size of the list is %d",size());

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

break; case 5: search(); break; case 6: exit(0); } } } void additem() { struct info *add; char proceed='y'; while(toupper(proceed)=='Y') { add=(struct info*)malloc(sizeof(struct info)); printf("Enter data:"); scanf("%d",&add->data); fflush(stdin); if(head==NULL) { head=add; add->next=NULL; add->prev=NULL; temp=add; } else { temp->next=add; add->prev=temp; add->next=NULL; temp=add; } printf("\nWant to proceed y/n"); proceed=getchar(); fflush(stdin); } } void delitem() { int x; struct info *p;; if(head==NULL) { printf("\nNo items in the list"); return;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

} printf("\nEnter the data to delete"); scanf("%d",&x); //fflush(stdin); p=(struct info *)malloc(sizeof(struct info)); p=head->next; if(head->data==x) { head=head->next; return; } while(p) { if(p->data==x) { p->prev->next=p->next; if(p->next!=NULL) p->next->prev=p->prev; else temp=p->prev; return; } else { p=p->next; } } printf("\nInvalid input"); } void display() { if(head==NULL) { printf("\nNo data to display"); return; } printf("\nFrom forward direction\n"); for(disp=head;disp!=NULL;disp=disp->next) { printf("Data->%d",disp->data); } printf("\nFrom backward direction\n"); for(disp=temp;disp!=NULL;disp=disp->prev) { printf("Data->%d",disp->data); }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

10

} int size() { int count=0; if(head==NULL) return count; for(disp=head;disp!=NULL;disp=disp->next) count++; return count; } void search() { int titem,found=0; if(head==NULL) { printf("\nNo data in the list"); return; } printf("\Enter the no. to search:"); scanf("%d",&titem); for(disp=head;disp!=NULL&&found==0;disp=disp->next) { if(disp->data==titem) found=1; } if(found==0) printf("\nSearch no. is not present in the list"); else printf("\nSearch no. is present in the list"); return; } OUTPUT:1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:1 Enter data:21 Want to proceed y/ny Enter data:23

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

11

Want to proceed y/ny Enter data:45 Want to proceed y/nn 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:3 From forward direction Data->21Data->23Data->45 From backward direction Data->45Data->23Data->21 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:2 Enter the data to delete23 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:4 The size of the list is 2 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:3 From forward direction Data->21Data->45 From backward direction Data->45Data->21 1.Add records

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

12

2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:5 Enter the no. to search:45 Search no. is present in the list 1.Add records 2.Delete records 3.Display records 4.Count no. of items in the list 5.Searching an item in the list 6.Exit Enter your choice:6 RESULT:The given program is implemented, executed, tested and verified successfully.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

13

2. POLYNOMIAL ADDITION AIM:To write a C program to represent a polynomial as a linked list and write functions for polynomial addition

ALGORITHM:1. Start the program 2. Get the coefficients and powers for the two polynomials to be added. 3. Add the coefficients of the respective powers. 4. Display the added polynomial. 5. Terminate the program.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

14

PROGRAM:#include<stdio.h> #include<conio.h> struct polynomial { int coff; int pow; struct polynomial *link; }*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2; typedef struct polynomial pnl; int temp1,temp2; void main() { void create(void); void prnt(void); void suml(void); void sort(void); clrscr(); printf("Enrter the elements of the first polynomial :"); node = (pnl *) malloc(sizeof (pnl)); start1=node; if (start1==NULL) { printf(" Unable to create memory."); getch(); exit(); } create(); printf("Enter the elements of the second poly :"); node = (pnl *) malloc(sizeof (pnl)); start2=node; if (start2==NULL) { printf("Unable to create memory."); getch(); exit(); } create(); clrscr(); //printing the elements of the lists printf("The elements of the poly first are :"); ptr=start1; prnt(); printf("The elements of the poly second are :");

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

15

ptr=start2; prnt(); printf("The first sorted list is :"); ptr=start1; sort(); ptr=start1; prnt(); printf("The second sorted list is :"); ptr=start2; sort(); ptr=start2; prnt(); printf("The sum of the two lists are :"); suml(); ptr=start3; prnt(); getch(); } /*-----------------------------------------------------------------------------*/ void create() { char ch; while(1) { printf(" Enter the coff and pow :"); scanf("%d%d",&node->coff,&node->pow); if (node->pow==0 ) { ptr=node; node=(pnl *)malloc(sizeof(pnl)); node=NULL; ptr->link=node; break; } printf("Do u want enter more coff ?(y/n)"); fflush(stdin); scanf("%c",&ch); if (ch=='n' ) { ptr=node; node=(pnl *)malloc(sizeof(pnl)); node=NULL; ptr->link=node; break; } ptr=node;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

16

node=(pnl *)malloc(sizeof(pnl)); ptr->link=node; } } /*-------------------------------------------------------------------------*/ void prnt() { int i=1; while(ptr!=NULL ) { if(i!=1) printf("+ "); printf(" %dx^%d\n ",ptr->coff,ptr->pow); ptr=ptr->link; i++; } //printf(" %d^%d",ptr->coff,ptr->pow); } /*---------------------------------------------------------------------------*/ void sort() { for(;ptr->coff!=NULL;ptr=ptr->link) for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link) { if(ptr->pow>ptr2->pow) { temp1=ptr->coff; temp2=ptr->pow; ptr->coff=ptr2->coff; ptr->pow=ptr2->pow; ptr2->coff=temp1; ptr2->pow=temp2; } } } /*---------------------------------------------------------------------------*/ void suml() { node=(pnl *)malloc (sizeof(pnl)); start3=node; ptr1=start1; ptr2=start2; while(ptr1!=NULL && ptr2!=NULL) {

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

17

ptr=node; if (ptr1->pow > ptr2->pow ) { node->coff=ptr2->coff; node->pow=ptr2->pow; ptr2=ptr2->link; //update ptr list B } else if ( ptr1->pow < ptr2->pow ) { node->coff=ptr1->coff; node->pow=ptr1->pow; ptr1=ptr1->link; //update ptr list A } else { node->coff=ptr2->coff+ptr1->coff; node->pow=ptr2->pow; ptr1=ptr1->link; //update ptr list A ptr2=ptr2->link; //update ptr list B } node=(pnl *)malloc (sizeof(pnl)); ptr->link=node; //update ptr list C }//end of while if (ptr1==NULL) //end of list A { while(ptr2!=NULL) { node->coff=ptr2->coff; node->pow=ptr2->pow; ptr2=ptr2->link; //update ptr list B ptr=node; node=(pnl *)malloc (sizeof(pnl)); ptr->link=node; //update ptr list C } } else if (ptr2==NULL) //end of list B { while(ptr1!=NULL) { node->coff=ptr1->coff; node->pow=ptr1->pow; ptr1=ptr1->link; //update ptr list B ptr=node; node=(pnl *)malloc (sizeof(pnl));

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

18

ptr->link=node; //update ptr list C } } node=NULL; ptr->link=node; } OUTPUT:Enrter the elements of the first polynomial : Enter the coff and pow :1 1 Do u want enter more coff ?(y/n)y Enter the coff and pow :1 0 Enter the elements of the second poly : Enter the coff and pow :1 1 Do u want enter more coff ?(y/n)y Enter the coff and pow :2 0 The elements of the poly first are : 1x^1 + 1x^0 The elements of the poly second are : 1x^1 + 2x^0 The first sorted list is : 1x^0 + 1x^1 The second sorted list is : 2x^0 + 1x^1 The sum of the two lists are : 3x^0 + 2x^1

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

19

3. CONVERT INFIX TO POSTFIX EXPRESSION

AIM:To write a C program to implement stack and use it to convert infix to postfix expression. ALGORITHM:1. Start the program 2. Scan the Infix string from left to right. 3. Initialise an empty stack. 4. If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack. y If the scanned character is an Operand and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned. 5. (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. 6. Return the Postfix string. 7. Terminate the program.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

20

PROGRAM:#include <stdio.h> #include <conio.h> #include <string.h> #include <ctype.h> char stack[100]; int top=0; char exp[100]; struct table { char s[2]; int isp; int icp; }pr[7]; int isp(char c) { int i; for(i=0;i<=6;i++) if(pr[i].s[0]==c) return(pr[i].isp); return 0; } int icp(char c) { int i; for(i=0;i<=6;i++) if(pr[i].s[0]==c) return(pr[i].icp); return 0; } void main() { int i; clrscr(); strcpy(pr[0].s,"^"); pr[0].isp=3; pr[0].icp=4; strcpy(pr[1].s,"*"); pr[1].isp=2; pr[1].icp=2; strcpy(pr[2].s,"/"); pr[2].isp=2; pr[2].icp=2;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

21

strcpy(pr[3].s,"+"); pr[3].isp=1; pr[3].icp=1; strcpy(pr[4].s,"-"); pr[4].isp=1; pr[4].icp=1; strcpy(pr[5].s,"("); pr[5].isp=0; pr[5].icp=4; strcpy(pr[6].s,"="); pr[6].isp=-1; pr[6].icp=0; clrscr(); stack[top]='='; printf("enter the infix expression"); gets(exp); i=0; printf("the postfix expression is ") while(i<strlen(exp)) { if(isalpha(exp[i])==0) { if(exp[i]==')') { while(stack[top]!='(') { printf("%c",stack[top]); top--; } top--; } else { while(isp(stack[top])>=icp(exp[i])) { printf("%c",stack[top]); top--; } top++; stack[top]=exp[i]; }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

22

} else printf("%c",exp[i]); i++; } while(top>0) { printf("%c",stack[top]); top--; } getch(); }

OUTPUT:enter the infix expression a*(s+d/f)+c the postfix expression is asdf/+*c+

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

23

4. IMPLEMENT ARRAY BASED CIRCULAR QUEUE AIM:To write a C program to implement array based circular queue and use it to simulate a producer-consumer problem ALGORITHM:1. Start the program 2. To insert an element, Step-i: If "rear" of the queue is pointing to the last position then go to step-ii or else step-iii Step-ii: make the "rear" value as 0 Step-iii: increment the "rear" value by one Step-iv: a. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-b b. insert the new value for the queue position pointed by the "rear" 3. To delete the particular item from circular queue Step-i: If the queue is empty then say "empty queue" and quit; else continue Step-ii: Delete the "front" element Step-iii: If the "front" is pointing to the last position of the queue then step-iv else step-v Step-iv: Make the "front" point to the first position in the queue and quit Step-v: Increment the "front" position by one 4. Terminate the program.

PROGRAM:-

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

24

PROGRAM:
#include<stdio.h> #include<conio.h> #include<stdlib.h> #define size 5 int queue[size]; int front=-1; int rear=0; int qfull() { if(front==(rear+1)%size) return 1; else return 0; } int qempty() { if(front==-1) return 1; else return 0; } void add(int item) { if(qfull()) printf("\n The circular queue is full!"); else { if(front==-1) front=rear=0;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

25

else rear=(rear+1)%size; queue[rear]=item; } } void delete() { int item; if(qempty()) printf("\n Queue is Empty!"); else { item=queue[front]; if(front==rear) { front=rear=-1; } else front=(front+1)%size; printf("\n The deleted item is %d",item); } } void display() { int i; if(qempty()) { printf("\n The Queue is empty"); return; } i=front;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

26

while(i!=rear) { printf("%d",queue[i]); i=(i+1)%size; } printf("%d",queue[i]); } void main(void) { int choice,item; char ans; clrscr(); do { printf("\n Main menu"); printf("\n 1.Insert\n 2.Delete\n 3.Display"); printf("\n Enter your choice:"); scanf("%d",&choice); switch(choice) { case 1:printf("\n Enter the element:"); scanf("%d",&item); add(item); break; case 2:delete(); break; case 3:display(); break; default:exit(0); } printf("\n Do you want to continue?");

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

27

ans=getch(); } while(ans=='y'||ans=='y'); getch(); }

OUTPUT:
Main menu 1.Insert 2.Delete 3.Display Enter your choice: 1 Enter the element : 100 Do you want to continue? Y

Main menu 1.Insert 2.Delete 3.Display Enter your choice: 1 Enter the element : 200 Do you want to continue? Y

Main menu

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

28

1.Insert 2.Delete 3.Display Enter your choice: 3 100 200 Do you want to continue? Y

Main menu 1.Insert 2.Delete 3.Display Enter your choice: 2 The deleted item is 100 Do you want to continue? Y

Main menu 1.Insert 2.Delete 3.Display Enter your choice: 3 200 Do you want to continue? N RESULT:The given program is implemented, executed, tested and verified successfully.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

29

5. IMPLEMENTATION OF TREE TRAVERSALS AIM:To write a C program to implement an expression tree. Produce its pre-order, in-order, andpost-ordertraversals.

ALGORITHM:Step 1: Start the process. Step 2: Initialize and declare variables. Step 3: Enter the choice. Inorder / Preorder / Postorder. Step 4: If choice is Inorder then o Traverse the left subtree in inorder. o Process the root node. o Traverse the right subtree in inorder. Step 5: If choice is Preorder then o Process the root node. o Traverse the left subtree in preorder. o Traverse the right subtree in preorder. Step 6: If choice is postorder then o Traverse the left subtree in postorder. o Traverse the right subtree in postorder. o Process the root node. Step7: Print the Inorder / Preorder / Postorder traversal. Step 8: Stop the process.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

30

PROGRAM #include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct treenode { int data; struct treenode *left; struct treenode *right; }tnode; tnode *insertion(int,tnode*); void preorder(tnode *); void inorder(tnode *); void postorder(tnode *); void main() { tnode *T=NULL; int ch1,n; char ch2; do { clrscr(); printf("\n\t\t****Operation With Tree****"); printf("\n\t1.Insertion"); printf("\n\t2.Inorder Traversal"); printf("\n\t3.Preorder Traversal"); printf("\n\t4.Postorder Traversal"); printf("\n\tEnter Your Choice :"); scanf("%d",&ch1); switch(ch1) { case 1: printf("\n\nenter the element to be inserted :"); scanf("%d",&n); T=insertion(n,T); break; case 2: inorder(T); break; case 3:

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

31

preorder(T);

break; case 4: postorder(T); break; default: printf("\n\nInvalid Option"); break; } printf("\n\nDo you want to continue y/n : "); scanf("%s",&ch2); }while(ch2=='y'); getch(); }

tnode *insertion(int x,tnode *T) { if(T==NULL) { T=(tnode *)malloc(sizeof(tnode)); if(T==NULL) printf("\nout of space"); else { T->data=x; T->left=T->right=NULL; } } else { if(x<(T->data)) T->left=insertion(x,T->left); else { if(x>T->data) T->right=insertion(x,T->right); } } return T; }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

32

void preorder(tnode *T) { if(T!=NULL) { printf("\t%d",T->data); preorder(T->left); preorder(T->right); } } void postorder(tnode *T) { if(T!=NULL) { postorder(T->left); postorder(T->right); printf("\t%d",T->data); } } void inorder(tnode *T) { if(T!=NULL) { inorder(T->left); printf("\t%d",T->data); inorder(T->right); } }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

33

6. IMPLEMENT BINARY SEARCH TREE

AIM:To write a C program to implement binary search tree.

ALGORITHM:Step 1: Start the process. Step 2: Initialize and declare variables. Step 3: Construct the Tree Step 4: Data values are given which we call a key and a binary search tree
Step 5: To search for the key in the given binary search tree, start with the root node and

Compare the key with the data value of the root node. If they match, return the root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by using

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

34

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

35

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

36

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)

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

37

{ 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 {

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

38

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

39

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

40

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

41

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

42

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

43

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

44

7. IMPLEMENTATION OF PRIORITY QUEUE USING HEAPS AIM:To implement priority queue using heaps.

ALGORITHM:Step 1: Start the Program Step 2: heap is a binary tree with two important properties: For any node n other than the root, n.key >= n.parent.key. In other words, the parent always has more priority than its children. If the heap has height h, the first h1 levels are full, and on the last level the nodes are all packed to the left. Step 4: implement the queue as a linked list, the element with most priority will be the first element of the list, so retrieving the content as well as removing this element are both O(1) operations. However, inserting a new object in its right position requires traversing the list element by element, which is an O(n) operation. Step 3: Insert Element in Queue void insert (Object o, int priority) - inserts in the queue the specified object with the specified priority Algorithm insert (Object o, int priority) Input: An object and the corresponding priority Output: The object is inserted in the heap with the corresponding priority lastNode getLast() //get the position at which to insert lastNode.setKey(priority) lastnode.setContent(o) n lastNode while n.getParent()! = null and n.getParent().getKey() > priority swap(n,n.getParent()) Step 4: Object DeleteMin() - removes from the queue the object with most priority Algorithm removeMin() lastNode <- getLast() value lastNode.getContent() swap(lastNode, root) update lastNode return value

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

45

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]);

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

46

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

47

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

48

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

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

49

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 67 34 24 67

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

50

8. IMPLEMENT HASHING TECHNIQUES AIM:To Implement the hashing techniques ALGORITHM:1. Start the program 2. Get the array size. 3. Get the elements of the array. 4. Get the key value of the element to be searched. 5. Find the position of the element by taking the remainder of the division of the array size by the key. 6. Print the element in that position. 7. Terminate the program.

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

51

PROGRAM:#include<stdio.h> #include<conio.h> #include<math.h> void main() { int a[125],key,size,i,h; clrscr(); printf("\n Enter the array size:"); scanf("%d",&size); printf("\n Enter the array element:"); for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("Enter the key value"); scanf("%d",&key); h=key%size; while(h!=i) i++; printf("The element is %d",a[i]); getch(); } OUTPUT: Enter the array size:4

Enter the array element:23 90 24 12 Enter the key value0 The element is 23

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

52

9. IMPLEMENTATION OF DIJKSTRA'S ALGORITHM USING PRIORITYQUEUES AIM: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 . 1 2 3 4 5 6 function Dijkstra(Graph, source): for each vertex v in Graph: dist[v] := infinity previous[v] := undefined dist[source] := 0 // Initializations

// Unknown distance function from source to v // Previous node in optimal path from source // Distance from source to source

Q := the set of all nodes in Graph // All nodes in the graph are unoptimized - thus are in Q

7 8 9

whileQis not empty:

// The main loop

u := vertex in Q with smallest dist[] if dist[u] = infinity:

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

53

10 11 12 13 14 15 16 17

break// all remaining vertices are inaccessible remove u from Q for each neighbor v of u: // where v has not yet been removed from Q.

alt := dist[u] + dist_between(u, v) ifalt< dist[v]: dist[v] := alt previous[v] := u return previous [] // Relax (u,v,a)

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

54

PROGRAM:#include<stdio.h> #include<stdlib.h> void main() { int graph[15][15],s[15],pathestimate[15],mark[15]; int num_of_vertices,source,i,j,u,predecessor[15]; int count=0; int minimum(int a[],int m[],int k); void printpath(int,int,int[]); printf("\nenter the no.of vertices\n"); scanf("%d",&num_of_vertices); if(num_of_vertices<=0) { printf("\nthis is meaningless\n"); exit(1); } printf("\nenter the adjacent matrix\n"); for(i=1;i<=num_of_vertices;i++) { printf("\nenter the elements of row %d\n",i); for(j=1;j<=num_of_vertices;j++) { scanf("%d",&graph[i][j]); } } printf("\nenter the source vertex\n"); scanf("%d",&source); for(j=1;j<=num_of_vertices;j++) { mark[j]=0; pathestimate[j]=999; predecessor[j]=0; } pathestimate[source]=0; while(count<num_of_vertices) { u=minimum(pathestimate,mark,num_of_vertices); s[++count]=u; mark[u]=1;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

55

for(i=1;i<=num_of_vertices;i++) { if(graph[u][i]>0) { if(mark[i]!=1) { if(pathestimate[i]>pathestimate[u]+graph[u][i]) { pathestimate[i]=pathestimate[u]+graph[u][i]; predecessor[i]=u; } } } } } for(i=1;i<=num_of_vertices;i++) { printpath(source,i,predecessor); if(pathestimate[i]!=999) printf("->(%d)\n",pathestimate[i]); } } int minimum(int a[],int m[],int k) { int mi=999; int i,t; for(i=1;i<=k;i++) { if(m[i]!=1) { if(mi>=a[i]) { mi=a[i]; t=i; } } } return t; }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

56

void printpath(int x,int i,int p[]) { printf("\n"); if(i==x) { printf("%d",x); } else if(p[i]==0) printf("no path from %d to %d",x,i); else { printpath(x,p[i],p); printf("..%d",i); } }

OUTPUT:

enter the no.of vertices 2 enter the adjacent matrix enter the elements of row 1 1 2 enter the elements of row 2 2 3 enter the source vertex 1 1->(0)

1..2->(2)

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

57

10.IMPLEMENTATION OF BACKTRACKING ALGORITHM FOR KNAPSACK PROBLEM AIM:To implement backtracking algorithm for Knapsack problem. ALGORITHM:function backtracking (current depth) if solution is valid return / print the solution else for each element from A[] source array let X[current depth] element if possible candidate (current depth + 1) backtracking (current depth + 1) end if end for end if end function (OR) Procedure knapsack: Initialize root; PQ <- root; max_cost := root.cost; while PQ not equal do current <- PQ; if (current.bound > max_cost) then create left_child := next item; if (left_child.cost > max_cost) max_cost := left_child.cost; update best_solution; end if; if (left_child.bound > max_cost) PQ <- left_child; end if; create right_child; // it skips packing the next item if (right_child.bound > max_cost) PQ <- right_child; end if; end if; end while; return best_solution and its cost;

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

58

end procedure;
PROGRAM:#include <stdio.h>

intn=5;/* The number of objects */ intc[10]={12,1,2,1,4};/* c[i] is the *COST* of the ith object; i.e. what YOU PAY to take the object */ intv[10]={4,2,2,1,10};/* v[i] is the *VALUE* of the ith object; i.e. what YOU GET for taking the object */ intW=15;/* The maximum weight you can take */ voidsimple_fill(){ intcur_w; floattot_v; inti,maxi; intused[10]; for(i=0;i<n;++i) used[i]=0;/* I have not used the ith object yet */ cur_w=W; while(cur_w>0){/* while there's still room*/ /* Find the best object */ maxi=-1; for(i=0;i<n;++i) if((used[i]==0)&& ((maxi==1)||((float)v[i]/c[i]>(float)v[maxi]/c[maxi]))) maxi=i; used[maxi]=1;/* mark the maxi-th object as used */ cur_w-=c[maxi];/* with the object in the bag, I can carry less */ tot_v+=v[maxi]; if(cur_w>=0) printf("Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n",maxi+1,v[maxi],c[maxi],cur_w); else{ printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n",(int)((1+(float)cur_w/c[maxi])*100),v[maxi],c[maxi],maxi+1); tot_v-=v[maxi]; tot_v+=(1+(float)cur_w/c[maxi])*v[maxi]; } } printf("Filled the bag with objects worth %.2f$.\n",tot_v); }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

59

intmain(intargc,char*argv[]){ simple_fill(); return0; }

www.EEENotes.in

--

DATA STRUCTURES AND ALGORITHMS LAB-131352

60

You might also like