Circular Queue using arrays
// In Circular Queue you can insert elements on the places of deleted elements.
Keep the note of (f+1)% n, (r+1)% n, (temp+1)% n in circular queue. These operations will be mostly used in circular Queue.
Keep the note of (f+1)% n, (r+1)% n, (temp+1)% n in circular queue. These operations will be mostly used in circular Queue.
Circular Queue are also known as "Ring Buffer" and have removed the drawback of linear queue, by inserting the elements at the deleted positions.
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
void enqueue(int a[], int *f, int *r, int n)
{
// n is the size of queue.
int data,choice=1;
while(choice==1){
if(*f==-1 && *r==-1)
{
*f=0;*r=0;
printf("enter the value to be inserted: ");
scanf("%d",&data);
a[*r]=data;
}
else if((*r+1)%n==*f)
{
printf("queue is full\n");
break;
}
else
{
*r=(*r+1)%n;
printf("enter the value to be inserted: ");
scanf("%d",&data);
a[*r]=data;
}
printf("want another element to be inserted(0,1): ");
scanf("%d",&choice);
}
}
void dequeue(int a[], int *f, int *r, int n)
{
int choice=1;
while(choice==1)
{
if(*f==-1 && *r==-1)
{
printf("Queue is empty\n");
break;
}
else if(*f==*r)
{
printf("Deleted element is: %d\n\nAnd Queue is now EMPTY\n",a[*f]);
*r=-1;*f=-1;
break;
}
else
{
printf("deleted element is %d\n",a[*f]);
*f=(*f+1)%n;
}
printf("Do you want another element to be deleted(0,1): ");
scanf("%d",&choice);
}
}
void display(int a[], int f, int r, int n)
{
int temp;
if(f==-1 && r==-1)
printf("Queue is empty\n");
else
{
temp=f;
printf("queue is:\n");
while(temp!=r)
{
printf("%d\n",a[temp]);
temp=(temp+1)%n;
}printf("%d\n",a[temp]);
}
}
void peek(int a[], int f, int r)
{
if(f==-1 && r==-1)
printf("Queue is empty\n");
else
printf("The element at front end is: %d\n",a[f]);
}
int main()
{
int frnt=-1, rear=-1,n,ch,choice=1;
printf("enter the size of queue: ");
scanf("%d",&n);
int queue[n];
while(choice==1){
printf("\nEnter 1. to enqueue(insert in queue) \n");
printf("Enter 2. to dequeue (to delete from queue)\n");
printf("Enter 3. to display \n");
printf("Enter 4. to peek (to show the element at front) \n choice: ");
scanf("%d",&ch);
if(ch==1)
enqueue(queue, &frnt, &rear, n);
else if(ch==2)
dequeue(queue, &frnt, &rear,n);
else if(ch==3)
display(queue, frnt, rear,n);
else if(ch==4)
peek(queue, frnt, rear);
else
printf("invalid choice:");
printf("\nDo you want to continue(0,1): ");
scanf("%d",&choice);
}
}
Please Do follow the blog if you liked the content.
ReplyDeleteNice
ReplyDelete