example1_implementation.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <stdexcept>

class Queue {
private:
    int* arr;
    int front;
    int rear;
    int capacity;
    int count;

public:
    Queue(int size) : capacity(size), front(0), rear(-1), count(0) {
        arr = new int[size];
    }

    ~Queue() {
        delete[] arr;
    }

    void enqueue(int x) {
        if (isFull()) {
            throw std::runtime_error("Queue is full");
        }
        rear = (rear + 1) % capacity;
        arr[rear] = x;
        count++;
    }

    int dequeue() {
        if (isEmpty()) {
            throw std::runtime_error("Queue is empty");
        }
        int x = arr[front];
        front = (front + 1) % capacity;
        count--;
        return x;
    }

    int peek() const {
        if (isEmpty()) {
            throw std::runtime_error("Queue is empty");
        }
        return arr[front];
    }

    int size() const {
        return count;
    }

    bool isEmpty() const {
        return (size() == 0);
    }

    bool isFull() const {
        return (size() == capacity);
    }
};

int main() {
    Queue q(5);

    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);

    std::cout << "Front element is: " << q.peek() << std::endl;
    std::cout << "Queue size is: " << q.size() << std::endl;

    std::cout << "Dequeuing: " << q.dequeue() << std::endl;
    std::cout << "Dequeuing: " << q.dequeue() << std::endl;

    q.enqueue(4);
    q.enqueue(5);
    q.enqueue(6);

    std::cout << "Queue size is: " << q.size() << std::endl;

    try {
        q.enqueue(7);
    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    while (!q.isEmpty()) {
        std::cout << "Dequeuing: " << q.dequeue() << std::endl;
    }

    try {
        q.dequeue();
    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}
Back to queue