-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueue.h
More file actions
executable file
·76 lines (65 loc) · 1.59 KB
/
Queue.h
File metadata and controls
executable file
·76 lines (65 loc) · 1.59 KB
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
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
using namespace std;
template <typename T> class Queue {
private:
T *arr;
size_t capacity;
int read;
int write;
size_t size;
public:
// Constructor
Queue() : capacity(10), read(0), write(0), size(0) { arr = new T[capacity]; }
Queue(size_t initialCapacity) {
capacity = initialCapacity;
arr = new T[capacity];
read = write = 0;
size = 0;
}
// Destructor
~Queue() { delete[] arr; }
// Function to enqueue an element
void enqueue(const T &element) {
arr[write] = element;
write = (write + 1) % capacity;
if (this->isFull())
{
read = (read - 1) % capacity;
return;
}
size++;
}
// Function to dequeue an element
void dequeue() {
if (isEmpty()) {
cerr << "Error: Queue is empty. Cannot dequeue.\n";
return;
}
if (read != write) {
read = (read + 1) % capacity;
size--;
// reset read and right
if (isEmpty()) {
read = write = 0;
}
}
}
// Function to get the element at the front of the queue
T frontElement() const {
if (isEmpty()) {
cerr << "Error: Queue is empty. No front element.\n";
exit(1);
}
return arr[read];
}
// Function to check if the queue is empty
bool isEmpty() const { return size == 0; }
// Function to check if the queue is full
bool isFull() const { return size == capacity; }
// Function to get the current size of the queue
size_t getSize() const { return size; }
T &operator[](size_t index) { return arr[(read + index) % capacity]; }
};
#endif // QUEUE_H