Circular Queue Data Structure algorithm by developerIndian

Updated:13/08/2023 by Computer Hope

Go Back


A circular queue is the extended version of a regular queue where the last element is connected to the first element.
In this tutorial, you will learn what a Circular queue is. Also, you will find implementation of queue in C, C++, Java and Python.

A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
#include<stdio.h>
#include<conio.h>
#define MAX 10
int queue[MAX];
int f=-1,r=-1;



void insertrear(int no)
  { if((f==0&&r==MAX-1)||(r+1==f))
     {
     printf("\nQueue is Full");
     return;  }
   else
     {  if(r==-1)
           f=r=0;
        else if(r==MAX-1)
           r=0;
        else
          r++;
        queue[r]=no;
      }
   }
int deletefront()
 { int val;
   if(f==-1)
     { printf("\nQueue is Empty");
       return -999;
      }
   else
    { val=queue[f];
       if(f==r)
          f=r=-1;
       else if(f==MAX-1)
          f=0;
       else
          f++;
     }
  return val;
  }
void show()
  {  int i=f;
    if(f==-1)
     {  printf("\nQueue is Empty");
        return; }
   while(i!=MAX)
     {  printf("%d  ",queue[i]);
        if(i==r)
          break;
        else if(i==MAX-1)
          i=0;
        else
          i++;
      }
}
void main()
{  int  ch,n;
   do
    {  printf("\n1. Insert in Rear");
       printf("\n2. Delete from Front");
       printf("\n3. Show");
       printf("\n0. Exit");
       printf("\n\nEnter Your Choice");
       scanf("%d",&ch);
       switch(ch)
         {
         case 1 : printf("\nEnter Number ");
	          scanf("%d",&n);
	          insertrear(n);
	          break;
         case 2 : n=deletefront();
	          if(n!=-999)
	             printf("\n%d deleted",n);
	          break;
         case 3 : show();
	           break;
         case  0 :break;
         default : printf("\nWrong Choice...Try Again");
       }
    }while(ch!=0);
}



      

Conclusion

Put an operation in queue. Verify whether the queue is full. Set the value of FRONT to 0 for the first element. progressively raise the REAR index by 1 (so that when the rear reaches the end, it will once again be at the front of the queue)...
Operation of Dequeue. Verify whether the queue is empty. return the value that Front directed to.