Queues in C++

Mannan Ul Haq
0

What is Queue?

A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. Think of it as a line of people waiting for a service; the first person in line is the first one to be served.

Operations:

1. Enqueue: Adds an element to the end of the queue.

2. Dequeue: Removes the front element from the queue.

3. IsEmpty: Checks if the queue is empty.

4. IsFull: Checks if the queue is full (only relevant for array-based implementations).


Example:


Here is a simple implementation of a queue using an array in C++:


#include <iostream>
using namespace std;

template <class T>
class Queue {
private:
    T* Array;
    int Max_Size;
    int Front_Index;
    int Rear_Index;
    int Current_Size;

public:
    // Constructor to initialize the queue
    Queue(int Size = 10) {
        this->Max_Size = Size;
        this->Array = new T[this->Max_Size];
        this->Front_Index = 0;
        this->Rear_Index = -1;
        this->Current_Size = 0;
    }

    // Destructor to clean up allocated memory
    ~Queue() {
        delete[] Array;
    }

    // Check if the queue is empty
    bool IsEmpty() {
        return Current_Size == 0;
    }

    // Check if the queue is full
    bool IsFull() {
        return Current_Size == Max_Size;
    }

    // Enqueue operation to add an element to the queue
    bool Enqueue(T value) {
        if (IsFull()) {
            cout << "Queue is full!" << endl;
            return false;
        }
        else {
            Rear_Index = (Rear_Index + 1) % Max_Size;
            Array[Rear_Index] = value;
            Current_Size++;
            return true;
        }
    }

    // Dequeue operation to remove the front element from the queue
    bool Dequeue() {
        if (IsEmpty()) {
            cout << "Queue is empty!" << endl;
            return false;
        }
        else {
            Front_Index = (Front_Index + 1) % Max_Size;
            Current_Size--;
            return true;
        }
    }
};

int main() {
    Queue<int> queue(5);

    queue.Enqueue(1);
    queue.Enqueue(2);
    queue.Enqueue(3);

    queue.Dequeue();

    return 0;
}
Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !