Queue using Array

 avatar
itsLu
c_cpp
2 months ago
2.0 kB
2
Indexable
Never
//constructor, isFull, enqueue, doubleSize, isEmpty, dequeue, getNumberOfElements, getMaxSize, getFront, displayQueue, destructor
#include <iostream>
using namespace std;

class queueArray
{
    int *arr, queueSize, frnt, rear, counter;
public:
    queueArray(int s = 1)
    {
        queueSize = s;
        arr = new int [queueSize];
        frnt = rear = counter = 0;
    }
    bool isFull()
    {
        return counter == queueSize;
    }
    void doubleSize()
    {
        int *tempArray = new int [queueSize * 2];
        for (int k = 0 ; k < queueSize ; k++)
            tempArray[k] = arr[(frnt+k)%queueSize];
        queueSize *= 2;
        delete [] arr;
        arr = tempArray;
        frnt = 0;
        rear = counter;
    }
    void enqueue (int item)
    {
        if (isFull())
            doubleSize();
        arr[rear] = item;
        rear = (rear + 1) % queueSize;
        counter++;
    }
    bool isEmpty()
    {
        return counter == 0;
    }
    int dequeue ()
    {
        if (isEmpty())
        {
            cout << "Queue is empty!\n";
            return -1;
        }
        counter--;
        int temp = frnt;
        frnt = (frnt + 1) % queueSize;
        return arr[temp];
    }
    int getNumberofElements ()
    {
        return counter;
    }
    int getMaxSize ()
    {
        return queueSize;
    }
    int getFront ()
    {
        return arr[frnt];
    }
    void displayQueue()
    {
        for (int k = 0 ; k < counter ; k++)
            cout << arr[(k + frnt)%queueSize] << "\t";
    }
    ~queueArray()
    {
        delete [] arr;
        cout << "\nQueue is deleted!";
    }
};

int main()
{
    queueArray queue1;
    for (int k = 0 ; k <= 10 ; k+=2)
        queue1.enqueue(k);
    queue1.displayQueue();
    cout << endl;
    cout << queue1.dequeue() << "\t" << queue1.dequeue() << endl;
    queue1.displayQueue();
    cout << endl << queue1.getMaxSize() << "\t" << queue1.getFront();
}
Leave a Comment