Circular Queue Implementation

 avatar
shebom640
c_cpp
a year ago
2.4 kB
2
Indexable
#include <stdio.h>
#include <stdlib.h>

// Circular Queue Implementation

int rear = -1;
int front = -1;

void
insert (int cqueue[], int item, int size)
{
  if ((front == 0 && rear == size - 1) || (front == rear + 1))
    {
      // Queue is full (overflow)
      printf ("Queue Overflow\n");
      exit (1);			// Exit the program
    }

  if (front == -1)
    {
      // First element, set front and rear to 0
      front = rear = 0;
    }
  else
    {
      if (rear == size - 1)
	rear = 0;		// Wrap around to the beginning
      else
	rear++;			// Increment rear normally
    }
  cqueue[rear] = item;
}

int
delete (int cqueue[], int size)
{
  if (front == -1)
    {
      // Queue is empty (underflow)
      printf ("Queue Underflow\n");
      exit (1);			// Exit the program
    }

  int x = cqueue[front];
  if (front == rear)
    {
      // Last element, reset front and rear to -1
      front = rear = -1;
    }
  else
    {
      if (front == size - 1)
	front = 0;		// Wrap around to the beginning
      else
	front++;		// Increment front normally
    }
  return x;
}

void
show (int cqueue[], int size)
{
  int front_pos = front, rear_pos = rear;

  if (front == -1)
    {
      printf ("\nQueue is empty\n");
      return;
    }

  printf ("\nQueue elements:\n");

  if (front_pos <= rear_pos)
    {
      while (front_pos <= rear_pos)
	{
	  printf ("%d ", cqueue[front_pos]);
	  front_pos++;
	}
    }
  else
    {
      while (front_pos <= size - 1)
	{
	  printf ("%d ", cqueue[front_pos]);
	  front_pos++;
	}
      front_pos = 0;
      while (front_pos <= rear_pos)
	{
	  printf ("%d ", cqueue[front_pos]);
	  front_pos++;
	}
    }
  printf ("\n");
}

int
main ()
{
  int size;
  printf ("Enter the size of the Circular Queue: ");
  scanf ("%d", &size);

  int cqueue[size];

  int choice, item;

  while (1)
    {
      printf ("\nCircular Queue Operations:\n");
      printf ("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
      printf ("Enter your choice: ");
      scanf ("%d", &choice);

      switch (choice)
	{
	case 1:
	  printf ("Enter the item to insert: ");
	  scanf ("%d", &item);
	  insert (cqueue, item, size);
	  break;
	case 2:
	  item = delete (cqueue, size);
	  printf ("Deleted item: %d\n", item);
	  break;
	case 3:
	  show (cqueue, size);
	  break;
	case 4:
	  exit (0);
	  break;
	default:
	  printf ("Invalid choice\n");
	}
    }

  return 0;
}