Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
1.5 kB
2
Indexable
Never
#include <iostream>
#define MAX_SIZE 100

class ArrayQueue {
private:
    int front, rear;
    int arr[MAX_SIZE];

public:
    ArrayQueue() {
        front = -1;
        rear = -1;
    }

    bool IsEmpty() {
        return (front == -1 && rear == -1);
    }

    bool IsFull() {
        return (rear == MAX_SIZE - 1);
    }

    void Enqueue(int x) {
        if (IsFull()) {
            std::cout << "Queue Overflow!" << std::endl;
            return;
        }
        if (IsEmpty()) {
            front = 0;
        }
        arr[++rear] = x;
        std::cout << "Enqueued: " << x << std::endl;
    }

    void Dequeue() {
        if (IsEmpty()) {
            std::cout << "Queue Underflow!" << std::endl;
            return;
        }
        std::cout << "Dequeued: " << arr[front] << std::endl;
        if (front == rear) {
            front = rear = -1; // Reset queue
        } else {
            front++;
        }
    }

    int Peek() {
        if (IsEmpty()) {
            std::cout << "Queue is empty!" << std::endl;
            return -1;
        }
        return arr[front];
    }
};

int main() {
    ArrayQueue q;

    q.Enqueue(10);
    q.Enqueue(20);
    q.Enqueue(30);

    std::cout << "Front element: " << q.Peek() << std::endl;

    q.Dequeue();
    q.Dequeue();
    q.Dequeue();

    q.Dequeue();  // Attempt to dequeue from empty queue

    return 0;
}
Leave a Comment