File

advertisement
CS2208
DATA STRUCTURES
AND ALGORITHMS
LAB MANUAL
CONTENTS
Ex
No
Name of the Experiment
1.a
Implementation of Singly Linked List
1.b
Implementation of Doubly Linked List
2
Representing a polynomial as linked list to perform polynomial addition
3.a
Implementation of stack using array
3.b
Implementation of stack for converting an infix expression to postfix
expression
4.a
Implementation of queue using array
4.b
Implementation of array based circular queue to simulate producerconsumer problem
5
Implementation of expression tree and its preorder, inorder and postorder
tree traversals
6
Implementation of Binary Search Trees
7
Implementation of Insertion in AVL Trees
8
Implementation of Priority Queue using Heaps
9
Implementation of Hashing
10
Implementation of Topological Sorting on directed acyclic graph
11.a
Implementation of Dijkstra’s Algorithm
11.b
Implementation of Dijkstra’s Algorithm using priority queues
12.a
Implementation of Prim’s algorithm for minimum spanning tree
12.b
Implementation of Krushkal’s algorithm minimum spanning tree
13
Implementation of Backtracking algorithm for Knapsack problem
14
Implementation of Branch and Bound algorithm for Travelling Salesperson
problem
15
Implementation of Random Number Generation using Randomized
Algorithms
Page
No
IMPLEMENTATION OF SINGLY LINKED LIST
AIM:To write a ‘C’ program to implement 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
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void insert (int x);
void deletion (int x);
void display ();
struct node
{
int element;
struct node *next;
} *list=NULL,*p;
struct node *find (int s)
{
p=list->next;
while (p!= NULL && p-> element!=s)
p=p-> next;
return p;
}
struct node *findprevious (int s)
{
p=list;
while(p->next!=NULL && p-> next->element !=s)
p=p->next;
return p;
}
void main()
{
int data, ch;
clrscr();
printf("\n\n 1.Insert \n\n 2. Delete \n\n 3. Display");
do
{
printf("\n\n Enter your choice.... ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter the element to be inserted ::");
scanf("%d",&data);
insert(data);
break;
case 2:
printf("\n\n Enter the element to be deleted::");
scanf("%d",&data);
deletion(data);
break;
case 3:
display();
break;
default:
printf("\n\n Invalid choice...");
getch();
exit(0);
}
}while (ch<4);
}
void insert (int x)
{
struct node *newnode;
intpos;
newnode=malloc(sizeof(struct node));
newnode->element = x;
if(list->next==NULL)
{
list->next = newnode;
newnode->next =NULL;
}
else
{
printf("\n\n Enter the value of the element to be inserted :: ");
scanf("%d",&pos);
p=find(pos);
newnode -> next=p ->next;
p -> next = newnode;
}
}
void deletion(int x)
{
struct node *temp;
temp = malloc(sizeof (struct node));
p = findprevious(x);
if(p ->next !=NULL)
{
temp =p-> next;
p-> next = temp-> next;
printf("\n\n Element %d is not found in the list", temp-> element);
free (temp);
}
else
printf("\n\n Element not found in the list!!!");
}
void display()
{
if(list -> next ==NULL)
printf("\n\n List is empty!!!");
else
{
p = list ->next ;
printf("\n\n The content of the list are \n ::");
while(p!=NULL)
{
printf("%d ->",p-> element);
p=p -> next;
}
}
}
OUTPUT:
1.
Insert
2. Delete
3. Display
Enter your choice :: 1
Enter the element to be inserted :: 4
Enter your choice :: 3
The contents of the list are :: 4 ->
Enter your choice :: 2
Enter the element to be deleted :: 4
Enter your choice :: 3
List is empty !!!
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF DOUBLY LINKED LIST
AIM:To write a ‘C’ program to create a Doubly linked list implementation.
ALGORITHM:1. Start the program.
2. Get the choice from the user.
3. If the choice is to add records, get the data from the user and add them
to the list.
4. If the choice is to delete records, get the data to be deleted and delete it
from the list.
5. If the choice is to display number of records, count the items in the list
and display.
6. 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
CODE:
#include<stdio.h>
#include<conio.h>
#define NULL 0
struct info
{
int data;
struct info *next;
struct info *prev;
};
struct info *head, *temp, *disp;
voidadditem();
voiddelitem();
void display();
int size();
void search();
void main()
{
int choice;
clrscr();
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");
while(1)
{
printf("\n\nEnter your choice: ");
scanf("%d", &choice);
fflush(stdin);
switch(choice)
{
case 1:
additem();
getch();
break;
case 2:
delitem();
getch();
break;
case 3:
display();
getch();
break;
case 4:
printf("The size of the list is %d", size());
getch();
break;
case 5:
search();
getch();
break;
case 6:
exit(0);
}
}
}
voidadditem()
{
struct info *add;
char proceed='y';
while (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("Want to proceed? (y/n) ");
proceed=getchar();
fflush(stdin);
}
}
voiddelitem()
{
int x;
struct info *p;
if(head==NULL)
{
printf("No item in the list");
return;
}
printf("Enter 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("Invalid input");
}
void display()
{
if(head==NULL)
{
printf("No data to display");
return;
}
printf("From forward direction:");
printf("\nData");
for(disp=head;disp!=NULL;disp=disp->next)
{
printf("->%d",disp->data);
}
printf("\nFrom backward direction:");
printf("\nData");
for(disp=temp;disp!=NULL;disp=disp->prev)
{
printf("->%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()
{
intitem,found=0;
if(head==NULL)
{
printf("No data in the list");
return;
}
printf("Enter the no. to search: ");
scanf("%d", &item);
for(disp=head;disp!=NULL && found==0; disp=disp->next)
{
if(disp->data==item)
found=1;
}
if(found==0)
printf("Search no. is not present in the list");
else
printf("Search 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: 5
Want to proceed? (y/n) y
Enter data: 7
Want to proceed? (y/n) y
Enter data: 3
Want to proceed? (y/n) n
Enter your choice: 3
From forward direction:
Data->5->7->3
From backward direction:
Data->3->7->5
Enter your choice: 2
Enter the data to delete: 7
Enter your choice: 3
From forward direction:
Data->5->3
From backward direction:
Data->3->5
Enter your choice: 4
The size of the list is 2
Enter your choice: 5
Enter the no. to search:5
Search no. is present in the list
Enter your choice: 6
[PROGRAM EXIT]
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF LINKED LIST TO PERFORM POLYNOMIAL ADDTION
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.
CODE:
#include<stdio.h>
#include<conio.h>
struct polynomial
{
intcoff;
intpow;
struct polynomial *link;
}*ptr, *start1, *node, *start2, *start3, *ptr1, *ptr2;
typedefstruct polynomial pnl;
int temp1, temp2;
void main()
{
void create(void);
voidprnt(void);
void sum1(void);
void sort(void);
clrscr();
printf("Enter the elements of the first polynomial...\n");
node=(pnl *)malloc(sizeof(pnl));
start1=node;
if(start1==NULL)
{
printf("Unable to create memory");
getch();
exit(0);
}
create();
printf("\nEnter the elements of the second polynomial...\n");
node=(pnl *)malloc(sizeof(pnl));
start2=node;
if(start2==NULL)
{
printf("Unable to create memory");
getch();
exit(0);
}
create();
clrscr();
//printing the elements of the list
printf("The elements of the first polynomial are...\n");
ptr=start1;
prnt();
printf("\n\nThe elements of the second polynomial are...\n");
ptr=start1;
prnt();
printf("\n\nThe first stored list is...\n");
ptr=start1;
sort();
ptr=start1;
prnt();
printf("\n\nThe second sorted list is...\n");
ptr=start2;
sort();
ptr=start2;
prnt();
printf("\n\nThe sum of the two lists is...\n");
sum1();
ptr=start3;
prnt();
getch();
}
void create()
{
charch;
while(1)
{
printf("Enter the coefficient and power: ");
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 you want to enter more coefficients?(y/n): ");
fflush(stdin);
scanf("%c", &ch);
if(ch=='n')
{
ptr=node;
node=(pnl *)malloc(sizeof(pnl));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(pnl *)malloc(sizeof(pnl));
ptr->link=node;
}
}
voidprnt()
{
int i=1;
while(ptr!=NULL)
{
if(i!=1)
printf("+");
printf("%dx^%d ", ptr->coff, ptr->pow);
ptr=ptr->link;
i++;
}
}
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 sum1()
{
node=(pnl*)malloc(sizeof(pnl));
start3=node;
ptr1=start1;
ptr2=start2;
while(ptr1!=NULL && ptr2!=NULL)
{
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
}
if(ptr1==NULL)
{
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)
{
while(ptr!=NULL)
{
node->coff=ptr->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list B
ptr=node;
node=(pnl*)malloc(sizeof(pnl));
ptr->link=node;
}
}
node=NULL;
ptr->link=node;
}
//update ptr list c
OUTPUT:
Enter the elements of the first polynomial...
Enter the coefficient and power: 1 1
Do you want to enter more coefficients?(y/n): y
Enter the coefficient and power: 1 0
Enter the elements of the second polynomial...
Enter the coefficient and power: 1 1
Do you want to enter more coefficients?(y/n): y
Enter the coefficient and power: 2 0
The elements of the first polynomial are...
1x^1 +1x^0
The elements of the second polynomial are...
1x^1 +1x^0
The first stored list is...
1x^0 +1x^1
The second sorted list is...
2x^0 +1x^1
The sum of the two lists is...
3x^0 +2x^1
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF STACK USIG ARRAY
AIM
To write a c program to implement stack using array
Stack Definition
In computer science, a stack is a last in, first out(LIFO) abstract data type and data
structure. A stack can have any abstract data type as an element, but is
characterized by only two fundamental operations, the push and the pop.
(or)
A collection of items in which only the most recently added item may be removed.
The latest added item is at the top. Basic operations are push and pop. Often top
and is Empty are available, too. Also known as "last-in, first-out" or LIFO.
Push:
The push operation adds to the top of the list, hiding any items already on the stack,
or initializing the stack if it is empty.
Pop:
The pop operation removes an item from the top of the list, and returns this value to
the caller. A pop either reveals previously concealed items, or results in an empty
list.
ALGORITHM
Step 1: Define a stack size.
Step 2: Read the stack operation.
Step 3: Read the stack element.
Step 4: Check the stack operation is Push or Pop.
Step 5: If operation is push then check the stack status.
i. If stack status is over flow we can’t push the element in to stack.
ii. Other wise we can add the data into stack .
iii. Move top to next position.
CODE
#include <stdio.h>
//#include <ctype.h>
#define MAXSIZE 5
int stack[MAXSIZE];
int top=0;
//index pointing to the top of stack
void main()
{
void push();
void pop();
void display();
int will=1,i;
clrscr();
while(1)
{
printf("\n\n\nMAIN
MENU:\n\n1.PUSH\n2.POP\n3.EXIT\n\nENTER YOUR CHOICE: ");
scanf("%d",&will);
switch(will)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
case 3:
exit(0);
break;
default:
printf("Invalid Choice . ");
}
} //end of outer while
}
//end of main
void push()
{
int num;
if(top>=MAXSIZE)
{
printf("\nSTACK FULL");
return;
}
else
{
if(top<0)
top=0;
printf("\n\nENTER THE STACK ELEMENT : ");
scanf("%d",&num);
stack[top++]=num;
}
}
void pop()
{
if(top>=0)
top--;
}
void display()
{
int i;
if(top<=0)
printf("\n\nSTACK EMPTY");
else
for(i=top-1;i>=0;i--)
{
printf("\n\n%d ",stack[i]);
if(i==(top-1))
printf("---->TOP");
}
}
SAMPLE OUTPUT
MAIN MENU
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 10
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 20
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 30
STACK FULL
30 ---->TOP
20
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
STACK EMPTY
RESULT:
Thus the ‘c’ program has been created and executed.
INFIX TO POSTFIX CONVERSION USING STACK
AIM
To write a c program to implement infix to postfix conversion using stack
ALGORITHM
1. Scan the Infix string from left to right.
2. Initialize an empty stack.
3. If the scanned character is an operand, add it to the Postfix string. If the
scanned character is an operator and if the stack is empty push the character
to stack.
4. If the scanned character is an Operator and the stack is not empty, compare
the precedence of the character with the element on top of the stack (top
Stack). If top Stack has higher precedence over the scanned character pop
the stack else push the scanned character to stack. Repeat this step as long
as stack is not empty and top Stack has precedence over the character.
5. Repeat this step till all the characters are scanned.
6. After all characters are scanned, we have to add any character that the stack
may have to the Postfix string. If stack is not empty add top Stack to Postfix
string and Pop the stack. Repeat this step as long as stack is not empty.
CODE
#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;
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];
}
}
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:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF QUEUE USING ARRAY
AIM
To write a c program to implement queue using array
Queue:
A Queue is a linear data structure which follows First In First Out (FIFO) principle, in
which insertion is performed at rear end deletion is performed at front end.
(or)
A queue is a "waiting line" type of data structure. Much like with a stack, we can
insert items into a queue and remove items from a queue. However, a queue has
"first come, first served" behavior in that the first item inserted into the queue is the
first one removed.
ALGORITHM:
Step 1: Initialize the queue variables front =0 and rear = -1
Step 2: Read the queue operation type.
Step 3: Check the queue operations status.
i). If it is Insertion then do the following steps
1. Check rear < queue_size is true increment the rear by one and read the
queue element and also display queue. other wise display the queue is full.
2. Go to step2.
ii). If it is deletion then do the following steps
1.
2.
3.
4.
5.
Check rear< front is true then display the queue is empty.
Move the elements to one step forward (i.e. move to previous index ).
Decreases the rear value by one (rear=rear-1).
Display queue
Go to step2.
CODE
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int i,rear,front,item,s[SIZE];
void insert(int item,int s[]);
void del(int s[]);
void display(int s[]);
void main()
{
int ch;
clrscr();
front=0;
rear=-1;
do
{
printf("\n\n 1.INSERTION \n 2.DELETION \n 3.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\t INSERTION \n");
if(rear>=SIZE-1)
{
printf("\t\nQUEUE IS FULL\n");
}
else
{
printf("\nENTER AN ELEMENT : ");
scanf("%d",&item);
insert(item,s);
}
display(s);
break;
case 2:
printf("\n\t DELETION \n");
if(front>rear)
{
printf("\t\nQUEUE IS EMPTY\n");
}
else
{
del(s);
}
display(s);
break;
}
}while(ch!=3);
getch();
}
void insert(int item,int s[])
{
if(rear<SIZE)
{
rear=rear+1;
s[rear]=item;
}
}
void del(int s[])
{
int i;
item=s[front];
for(i=0;i<=rear;i++)
s[i]=s[i+1];
rear--;
printf("\n DELETED ELEMENT IS %d\n\n",item);
}
void display(int s[])
{
printf("\n");
for(i=front;i<=rear;i++)
{
printf(" \t %d",s[i]);
}
}
OUTPUT:
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 10
10
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 20
10 20
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 30
10
20
30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
QUEUE IS FULL
10
20
30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 10
20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 20
30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
QUEUE IS EMPTY
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF CIRCULAR QUEUE FOR PRODUCER-CONSUMER
PROBLEM
AIM:
To write a c program to implement circular queue for producer consumer problem
DEFINITION:
An implementation of a bounded queue using an array.
(or)
In circular queue, the insertion of a new element is performed at the very first
location of the queue if the last location of the queue is full, in which the first
element comes just after the last element.
ALGPRITHM
Step 1: create and set the variables front,rear,MAXSIZE,cq[]
step 2: Read the circular queue opeartion type.
step 3: If operation type is Insertion below steps are executed.
1. Assign rear=rear%MAXSIZE.
2. if front equal to (rear+1)%MAXSIZE then display queue is
overflow.
3. if front equal to -1 then assign front=rear=0.
4. Otherwise assign rear=(rear+1)%MAXSIZE and read queue data .
5. Assign cq[rear] as data.(i.e. cq[rear]=data).
step 4: If operation type is Deletion below steps are executed.
1. Check front=-1 then display queue is underflow.
2. Set temp as cq[front] (i.e. temp=ca[front]).
3. Check front equal to rear if it is true then assign front=rear=-1(Move the
front to begining)
4. Assign front=(front+1)%MAXSIZE.
CODE:
#include<stdio.h>
#include<conio.h>
#include<process.h>
int frnt=-1,rear=-1,buffer[5];
void consume()
{
if(frnt==-1)
printf("\ncannot consume till producer produces it:");
else
{
printf("the consumed item is:%d",buffer[frnt]);
if(frnt==rear)
frnt=rear=-1;
else
frnt=((frnt+1)%5);
}
getch();
}
void producer(int x)
{
if(frnt==(rear+1)%5)
{
printf("\ncannot produce till consumer consumes it");
}
else
{
if(frnt==-1)
frnt=rear=0;
else
rear=((rear+1)%5);
buffer[rear]=x;
printf("\nthe produced element is:%d",buffer[rear]);
}
getch();
}
void disp()
{
int i;
printf("\nthe buffer contains:");
if(rear>=frnt)
{
for(i=frnt;i<=rear;++i)
printf("%d\t",buffer[i]);
}
else
{
for(i=frnt;i<5;++i)
printf("%d\t",buffer[i]);
for(i=0;i<=rear;++i);
printf("%d\t",buffer[i]);
}
getch();
}
void main()
{
int ch,z;
do
{
clrscr();
printf("\nproducer and consumer");
printf("\n1.produce an item");
printf("\n2.consume an item");
printf("\n3.display iteams");
printf("\n4.exit");
printf("\nenter the choice:");
scanf("\t%d",&ch);
switch(ch)
{
case 1:
printf("\nenter item to be inserted in buffer");
scanf("%d",&z);
producer(z);
break;
case 2:
consume();
break;
case 3:
disp();
break;
case 4:
exit(0);
break;
}
} while(ch<=4);
}
OUTPUT:
Program for circular Queue demonstration through array
MAIN MENU:
1. Add element to circular queue
2. Delete element from the circular queue
3. Display the contents of the queue
Enter your choice: 1
Enter the data: 15
Do you want to do more operation on circular queue?
(1 for Yes, any other key to exit): 1
Enter your choice: 1
Enter the data: 9
Do you want to do more operation on circular queue?
(1 for Yes, any other key toexit): 1
Enter your choice: 1
Enter the data: 5
Do you want to do more operation on circular queue?
(1 for Yes, any other key to exit): 1
Enter your choice: 3
The contents of the queue are...
15
9
5
Do you want to do more operation on circular queue?
(1 for Yes, any other key to exit): 1
Enter your choice: 2
The deleted value is 15
Do you want to do more operation on circular queue?
(1 for Yes, any other key to exit): 1
Enter your choice: 3
The contents of the queue are...
9
5
Do you want to do more operation on circular queue? (1 for Yes, any other key
:
RESULT:
Thus the ‘c’ program has been created and executed.
EXPRESSION TREE AND TREE TRAVERSALS
AIM:
To write a c program to implement expression tree and tree traversals
Definition:
It is a most common operation in binary tree. (i.e. pass through the tree).
Enumerating each of its nodes once. It is generally known as of visiting each node at
once.
Three type of traversing orders:
1. Preorder traversing.
2. Inorder traversing.
3. Postoredr traversing.
Algorithm Steps:
Step1: Builds the binary tree.
Step 2: Determain the tree is non empty.
Step 3: Traversing type is preorder (depth-first order) then perform the following
operations.
1. Visit the root.
2. Traverse the left subtree in preorder.
3. Traverse the right subtree in preorder.
Step 4: Traversing type is inorder (symmetric order) then performing the following
operations.
1. Traverse the left subtree in inorder.
2. Visit the root.
3. Traverse the right subtree in inorder.
Step 5: Traversing type is postorder then performing the following operations.
1. Traverse the left subtree in postorder.
2. Traverse the right subtree in postorder.
3. Visit the root.
CODE:
#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;
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");
do
{
printf("\nEnter your choice: ");
scanf("%d", &ch1);
switch(ch1)
{
case 1:
printf("\nEnter the element to be inserted: ");
scanf("%d", &n);
T=insertion(n,T);
break;
case 2:
inorder(T);
break;
case 3:
preorder(T);
break;
case 4:
postorder(T);
break;
default:
printf("\nInvalid Option");
break;
}
printf("\nDo you want to continue(y/n): ");
scanf("%c", &ch2);
scanf("%c", &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->right);
else
{
if(x>T->data)
T->right=insertion(x,T->right);
}
}
return T;
}
void preorder(tnode *T)
{
if(T!=NULL)
{
printf("%d\t", T->data);
preorder(T->left);
preorder(T->right);
}
}
void postorder(tnode *T)
{
if(T!=NULL)
{
postorder(T->left);
postorder(T->right);
printf("%d\t", T->data);
}
}
void inorder(tnode *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d\t", T->data);
inorder(T->right);
}
}
OUTPUT:
1.
2.
3.
4.
****OPERATION WITH TREE****
Insertion
Inorder Traversal
Preorder Traversal
Postorder Traversal
Enter your choice: 1
Enter the element to be inserted: 6
Do you want to continue(y/n): y
Enter your choice: 1
Enter the element to be inserted: 5
Do you want to continue(y/n): y
Enter your choice: 1
Enter the element to be inserted: 8
Do you want to continue(y/n): y
Enter your choice: 2
5
6
8
Do you want to continue(y/n): y
Enter your choice: 3
6
5
8
Do you want to continue(y/n): y
Enter your choice: 4
5
8
6
Do you want to continue(y/n):
RESULT:
Thus the ‘c’ program has been created and executed
IMPLEMENTATION OF BINARY SEARCH TREE
AIM
To write a c program to implement binary search tree
ALGORITHM:
Step 1: Start the process.
Step 2: Initialize and declare variables.
Step 3: Construct the Tree
Step 4: Data values are given which we call a key and a binary search tree
Step 5: To search for the key in the given binary search tree, start with the root
node and Compare the key with the data value of the root node. If they match,
return the root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by
using the left subtree.
Step 7: Otherwise, repeat the same process with the right subtree until either a
match is found or the subtree under consideration becomes an empty tree.
Step 8: Terminate
CODE
#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;
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;
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create a newtree\n2.Insert\n3.Delete\n4.Find\n5.Find Minimum
element\n6.Find Maximuum element\n7.Exit\n");
do
{
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the root node element: ");
scanf("%d",&element);
t=create(t,element);
break;
case 2:
printf("\nEnter the element to insert: ");
scanf("%d",&element);
t=insert(t,element);
break;
case 3:
printf("\nEnter the element to delete: ");
scanf("%d",&element);
t=del(t,element);
break;
case 4:
printf("\nEnter the element to be found: ");
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("\nMinimum element = %d",temp->data);
break;
case 6:
temp=findmax(t);
printf("\nMaximum element = %d",temp->data);
break;
case 7:
exit(0);
}
}while(ch<=7);
}
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* 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;
}
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;
}
OUTPUT:
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create a new tree
2.Insert
3.Delete
4.Find
5.Find Minimum element
6.FindMaximuum element
7.Exit
Enter your choice: 1
Enter the root node element: 8
Enter your choice: 2
Enter the element to insert: 5
Enter your choice: 2
Enter the element to insert: 11
Enter your choice: 4
Enter the element to be found: 11
Element 11 is found
Enter your choice: 5
Minimum element = 5
Enter your choice: 6
Maximum element = 11
Enter your choice: 3
Enter the element to delete: 5
Enter your choice: 7
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF INSERTION IN AVL TREES
AIM:
To write a ‘c’ program to implement insertion in AVL Trees
ALGORITHM








Start the program.
Start inserting elements into an empty AVL tree.
Follow binary search tree condition for each and every element to be inserted.
Check for balancing condition.
L=R+1 R=L+1.
If balancing factor perishes, go for rotation balancing factor can be,
Height Factor = Left-Right
If Height Factor is -1, 0, +1 no need for rotation.
If Height Factor is 2 0r -2 go for rotation.
Apply single rotation and know to the results, if single rotation fails to balance
then go for double rotation.
Display the results (or) inserted elements in post-order traversal.
Stop the program.
CODE
#include<stdio.h>
#include<conio.h>
typedef int ElementType;
struct AvlNode;
typedef struct AvlNode *Position;
typedef struct AvlNode *AvlTree;
AvlTree MakeEmpty( AvlTree T );
AvlTree Insert( ElementType X, AvlTree T );
void display(AvlTree T);
struct AvlNode
{
ElementType Element;
AvlTree Left;
AvlTree Right;
int Height;
};
void display(AvlTree T)
{
if(T->Left!=NULL)
display(T->Left);
if(T->Right!=NULL)
display(T->Right);
printf("%d",T->Element);
}
AvlTree MakeEmpty( AvlTree T )
{
if( T != NULL )
{
MakeEmpty( T->Left );
MakeEmpty( T->Right );
free( T );
}
return NULL;
}
static int Height( Position P )
{
if( P == NULL )
return -1;
else
return P->Height;
}
static int Max( int Lhs, int Rhs )
{
return Lhs > Rhs ? Lhs : Rhs;
}
static Position SingleRotateWithLeft( Position K2 )
{
Position K1;
K1 = K2->Left;
K2->Left = K1->Right;
K1->Right = K2;
K2->Height = Max( Height( K2->Left ), Height( K2->Right ) ) + 1;
K1->Height = Max( Height( K1->Left ), K2->Height ) + 1;
return K1;
}
static Position SingleRotateWithRight( Position K1 )
{
Position K2;
K2 = K1->Right;
K1->Right = K2->Left;
K2->Left = K1;
K1->Height = Max( Height( K1->Left ), Height( K1->Right ) ) + 1;
K2->Height = Max( Height( K2->Right ), K1->Height ) + 1;
return K2;
}
static Position DoubleRotateWithLeft( Position K3 )
{
K3->Left = SingleRotateWithRight( K3->Left );
return SingleRotateWithLeft( K3 );
}
static Position DoubleRotateWithRight( Position K1 )
{
K1->Right = SingleRotateWithLeft( K1->Right );
return SingleRotateWithRight( K1 );
}
AvlTree Insert( ElementType X, AvlTree T )
{
if( T == NULL )
{
T =(AvlTree) malloc( sizeof( struct AvlNode ) );
if( T == NULL )
printf( "Out of space!!!" );
else
{
T->Element = X; T->Height = 0;
T->Left = T->Right = NULL;
}
}
else
if( X < T->Element )
{
T->Left = Insert( X, T->Left );
if( Height( T->Left ) - Height( T->Right ) == 2 )
if( X < T->Left->Element )
T = SingleRotateWithLeft( T );
else
T = DoubleRotateWithLeft( T );
}
else
if( X > T->Element )
{
T->Right = Insert( X, T->Right );
if( Height( T->Right ) - Height( T->Left ) == 2 )
if( X > T->Right->Element )
T = SingleRotateWithRight( T );
else
T = DoubleRotateWithRight( T );
}
T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1;
return T;
}
main()
{
AvlTree T;
Position P;
int i=0,a,ch;
clrscr();
T = MakeEmpty( NULL );
while(1)
{
printf("\nEnter your choice 1.Insert 2.Display 3.Exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the element");
scanf("%d",&a);
T = Insert( a, T );
break;
case 2:
printf("Display by POSTORDER traversal\n");
display(T);
break;
case 3:
exit(0);
break;
}}
}
SAMPLE OUTPUT
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
1
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
2
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
3
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
4
Enter your choice 1.Insert 2.Display 3.Exit
2
Display by POSTORDER traversal
1432
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
5
Enter your choice 1.Insert 2.Display 3.Exit
2
Display by POSTORDER traversal
13542
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
6
Enter your choice 1.Insert 2.Display 3.Exit
1
Enter the element
7
Enter your choice 1.Insert 2.Display 3.Exit
2
Display by POSTORDER traversal
1325764
Enter your choice 1.Insert 2.Display 3.Exit
3
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF PRIORITY QUEUE USING HEAPS
AIM
To write a c program to implement Priority queues
ALGORITHM







Start the program.
Begin inserting elements into priority queue.
Follow both structural property and heap order property.
Make sure that recently inserted element found its right position as per
structural property.
Ensure that heap order property is preserved (ie) the smallest element must
be right on root.
Perform deletemin, Always the root element must be deleted and preserve
structure.
Perform perculate down till the actual position found for the element leaves
its space for making sure structure property.
CODE
#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)
{
int i;
if(isEmpty(h))
{
printf("\nPriority queue is empty");
return;
}
else
for(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();
printf("\n1. Insert\n2. DeleteMin\n3. Display\n4. Exit");
while(1)
{
printf("\nEnter your 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);
}
}
}
SAMPLE OUTPUT
Enter the Size of the Priority queue: 10
1. Insert
2. DeleteMin
3. Display
4. Exit
Enter your choice: 1
Enter the element: 4
Enter your choice: 1
Enter the element: 3
Enter your choice: 1
Enter the element: 5
Enter your choice: 3
3
4
5
Enter your choice: 1
Enter the element: 6
Enter your choice: 1
Enter the element: 2
Enter your choice: 3
2
3
5
6
Enter your choice: 2
Deleted element is 2
Enter your choice: 3
3
4
5
6
Enter your choice:
4
4
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF HASHING
AIM
To write a c program to implement hashing
ALGORITHM






Start the program.
Define hash table size.
Get the elements to be stored with key.
Perform
Position=key % table size.
Find the position, where the element has to be placed.
Making sure there is no collision after storing all the elements into hash table.
CODE
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[125],key,size,i,h;
clrscr();
printf("Enter the array size:");
scanf("%d",&size);
printf("\nEnter the elements for the array…");
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();
}
SAMPLE OUTPUT
Enter the array size:10
Enter the elements for the array
4
5
6
7
8
1
2
3
9
10
Enter the key value: 5
The element is 1
RESULT:
Thus the ‘c’ program has been created and executed.
IMPLEMENTATION OF MINIMUM SPANNING TREE USING PRIM’S
ALGORITHM
AIM:
To write a c program to implement minimum spanning tree using prim’s algorithm
ALGORITHM







Start the program.
Define a graph with required vertices and edges with cost normally or
undirected graph.
Select a source vertex, and find all its neighbours and update the path as
source for all neighbours with respective cost.
Take the vertex, which has minimum cost, find all its neighbours and update
the cost if lesser than earlier one..
Continue till last unknown vertex make to be known (or) visited.
Find the total cost, required to traverse all the vertices from source.
Stop the work.
CODE
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
int data;
struct node *par;
};
struct node *n[20];
struct edge
{
int wt;
struct node *src,*des;
};
struct edge *e[20][20];
void makeset(int i)
{
n[i]=(struct node *)malloc(sizeof(struct node));
n[i]->data=i;
n[i]->key=9999;
n[i]->par=NULL;
}
int main()
{
int tn,i,adm[20][20],q[20],s,j,w,temp,k;
printf("Enter the total no. of nodes ");
scanf("%d",&tn);
for(i=0;i<=tn;i++)
{
for(j=0;j<=tn;j++)
{
adm[i][j]=0;
}
}
printf("\nEnter the weights for the following edges ::\n");
for(i=1;i<=tn;i++)
{
makeset(i);
q[i]=i;
for(j=i+1;j<=tn;j++)
{
printf("%d %d: ",i,j);
scanf("%d",&w);
if(w==0)
w=9999;
e[i][j]=(struct edge *)malloc(sizeof(struct edge));
e[i][j]->wt=w;
e[i][j]->src=n[i];
e[i][j]->des=n[j];
adm[i][j]=1;
adm[j][i]=1;
}
}
j=1;
while(j<=tn)
{
q[j]=0;
temp=j;
for(k=1;k<=tn;k++)
{
if(adm[temp][k]==1 && q[k]==k)
{
if(e[temp][k]->wt<n[k]->key)
{
n[k]->par=n[temp];
n[k]->key=e[temp][k]->wt;
}
}
}
j++;
}
for(j=2;j<=tn;j++)
{
k=(n[j]->par)->data;
printf("output is %d : %d - %d\n",k,j,e[k][j]->wt);
}
getch();
}
SAMPLE OUTPUT
Enter the total no. of nodes 7
Enter the weights for the following edges ::
1 2: 2
1 3: 4
1 4: 1
1 5: 0
1 6: 0
1 7: 0
2 3: 0
2 4: 3
2 5: 10
2 6: 0
2 7: 0
3 4: 2
3 5: 0
3 6: 5
3 7: 0
4 5: 7
4 6: 8
4 7: 4
5 6: 0
5 7: 6
6 7: 1
output
output
output
output
output
output
is
is
is
is
is
is
1
1
1
4
3
6
:
:
:
:
:
:
2
3
4
5
6
7
-2
-4
-1
-7
-5
–1
TOTAL DISTANCE : 2+4+1+7+5+1 = 20
RESULT:
Thus the ‘c’ program has been created and executed.
Download