Circular Queue

This code is heavily derived from Circular Queue

In [1]:
#include <iostream>

using namespace std;
struct Queue {
    // Initialize front and rear 
    int rear, front;

    // Circular Queue 
    int size;
    int *arr;

    Queue(int s) {
        front = rear = -1;
        size = s;
        arr = new int[s];
    }

    void enQueue(int value);
    int deQueue();
    void displayQueue();
};
In [2]:
/* Function to create Circular queue */
void Queue::enQueue(int value) {
    if ((front == 0 && rear == size - 1) ||
        (rear == (front - 1) % (size - 1))) {
        std::cout << "Queue is Full" << std::endl;
        return;
    } else if (front == -1) /* Insert First Element */
    {
        front = rear = 0;
        arr[rear] = value;
    } else if (rear == size - 1 && front != 0) {
        rear = 0;
        arr[rear] = value;
    } else {
        rear++;
        arr[rear] = value;
    }
}
In [3]:
// Function to delete element from Circular Queue 
int Queue::deQueue() {
    if (front == -1) {
        std::cout << "Queue is Empty" << std::endl;
        return INT_MIN;
    }

    int data = arr[front];
    arr[front] = -1;
    if (front == rear) {
        front = -1;
        rear = -1;
    } else if (front == size - 1)
        front = 0;
    else
        front++;

    return data;
}
In [4]:
// Function displaying the elements 
// of Circular Queue 
void Queue::displayQueue() {
    if (front == -1) {
        std::cout << "Queue is Empty" << std::endl;
        return;
    }
    std::cout << "Elements in Circular Queue are: ";
    if (rear >= front) {
        for (int i = front; i <= rear; i++)
            std::cout << arr[i] << " ";
    } else {
        for (int i = front; i < size; i++)
            std::cout << arr[i] << " ";

        for (int i = 0; i <= rear; i++)
            std::cout << arr[i] << " ";
    }
}
In [5]:
Queue q(5);

// Inserting elements in Circular Queue 
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);

q.displayQueue();
Elements in Circular Queue are: 14 22 13 -6 
In [6]:
// Deleting elements from Circular Queue
std::cout << q.deQueue() << " ";
std::cout << q.deQueue() << " ";
14 22 
In [7]:
q.displayQueue();
Elements in Circular Queue are: 13 -6 
In [8]:
q.enQueue(9);
q.enQueue(20);
q.enQueue(5);

q.displayQueue();
Elements in Circular Queue are: 13 -6 9 20 5 
In [9]:
q.enQueue(10);
Queue is Full
In [10]:
q.displayQueue();
Elements in Circular Queue are: 13 -6 9 20 5