Circular Queue - C/C++

In a standard queue data structure re-buffering problem occurs for each dequeue operation. To solve this problem by joining the front and rear ends of a queue to make the queue as a circular queue
Circular queue is a linear data structure. It follows FIFO principle.
  • In circular queue the last node is connected back to the first node to make a circle.
  • Circular linked list fallow the First In First Out principle
  • Elements are added at the rear end and the elements are deleted at front end of the queue
  • Both the front and the rear pointers points to the beginning of the array.
  • It is also called as “Ring buffer”.
  • Items can inserted and deleted from a queue in O(1) time.
Circular Queue can be created in three ways they are
  • · Using single linked list
  • · Using double linked list
  • · Using arrays

#include<stdio.h>
#include<conio.h>
#define max 5
int q[max];
int rear = -1, front = -1;
void insert();
void delet();
void display();
 
void main()
{
 char ch;
 int choice;
 do
 {
  clrscr();
  printf("\n1 -> Insert");
  printf("\n2 -> Delete");
  printf("\n3 -> Display");
  printf("\n0 -> Exit");
 
  printf("\n\nEnter Your Choice -> ");
  scanf("%d", &choice);
  switch (choice)
  {
  case 1:
   insert();
   break;
  case 2:
   delet();
   break;
  case 3:
   display();
   break;
  case 0:
   exit();
  default:
   printf("\n\nInvalid Choice");
  }
  printf("\n\nDo u Want to Continue -> ");
  ch = getche();
 } while (ch == 'y' || ch == 'Y');
}
 
void insert()
{
 int data;
 if ((rear == max - 1 && front == 0) || rear == front - 1)
 {
  printf("\nSorry! Q is Full");
 }
 else
 {
  printf("\nEnter data You want to insert ->");
  scanf("%d", &data);
  if (front == -1)
  {
   front++;
   rear++;
  }
  else if (rear == max - 1)
  {
   rear = 0;
  }
  else
  {
   rear++;
  }
  q[rear] = data;
  printf("\n\nData inserted successfully");
 }
}
void delet()
{
 if (front == -1)
 {
  printf("\n\nSorry! Q is Empty");
 }
 else
 {
  if (front == rear)
  {
   front = rear = -1;
  }
  else if (front == max - 1)
  {
   front = 0;
  }
  else
  {
   front++;
  }
  printf("\nElement deleted Successfully");
 }
}
 
void display()
{
 int i;
 if (front == -1)
 {
  printf("\n\nSorry! Q is Empty");
 }
 else
 {
  printf("\n\n:: Queue Elements are ::\n");
  if (front <= rear)
  {
   for (i = front; i <= rear; i++)
   {
    printf("\n%d", q[i]);
   }
  }
  else
  {
   for (i = front; i < max; i++)
   {
    printf("\n%d", q[i]);
   }
   for (i = 0; i <= rear; i++)
   {
    printf("\n%d", q[i]);
   }
  }
 }
}

Check out other programs of queue here :
1. Priority Queue in C
2. Circular Queue in C
3. Operation on Queue [ Linked List ]
4. Operation on Queue [ Array ]

3 comments

Post a Comment