CIRCULAR QUEUE
To implement a circular queue data structure using an array, we first perform the following steps before we implement actual operations.
Step 1 - Include all the header files which are used in the program and define a constant 'MAX' with specific value.
Step 2 - Declare all user defined functions used in circular queue implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int queue[MAX])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1, rear = -1)
Step 5 - Implement main method by displaying menu of operations list and make suitable function calls to perform operation selected by the user on circular queue.
IMPLEMENTATION OF CIRCULAR QUEUE USING C LANGUAGE:-
#include<stdio.h>
#define MAX 5
void en_queue();
void de_queue();
void display();
int queue[MAX];
int rear = -1;
int front = -1;
main(){
int choice, n;
while(1){
printf("enter the choice\n");
printf("1. enqueue\n2. dequeue\n3. display\n4. exit\n");
scanf("%d",&choice);
switch(choice){
case 1:
en_queue();
break;
case 2:
de_queue();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
}
}
}
void en_queue(){
int n;
if((front == 0 && rear == MAX-1) || (front>0&&rear==front-1))
printf("queue overflow\n");
else if(rear == -1){
rear = front = 0;
printf("enter the number ");
scanf("%d",&n);
queue[rear] = n;
}
else{
rear = (rear+1) % MAX;
printf("enter the number ");
scanf("%d",&n);
queue[rear] = n;
}
}
void de_queue(){
if(rear == -1)
printf("queue is underflow\n");
else if(front == rear)
rear = front = -1;
else
front = (front + 1) % MAX;
}
void display(){
int i = front;
if(rear == -1)
printf("queue is underflow\n");
else{
while(i != rear){
printf("%d\n",queue[i]);
i = (i+1)%MAX;
}
printf("%d\n",queue[i]);
}
}
please give your comments regarding this.
Comments
Post a Comment