-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueusingArray.cpp
98 lines (80 loc) · 2.18 KB
/
QueueusingArray.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
97
98
#include <iostream>
using namespace std;
class Queue {
private:
int frontIdx; // Index of the front element
int rearIdx; // Index of the rear element
int capacity; // Maximum capacity of the queue
int* arr; // Array to store elements
int size; // Current number of elements in the queue
public:
// Constructor to initialize the queue
Queue(int capacity) {
this->capacity = capacity;
arr = new int[capacity];
frontIdx = 0;
rearIdx = -1;
size = 0;
}
// Destructor to free the dynamically allocated memory
~Queue(){
delete[]arr;
}
// Function to add an element to the rear of the queue (enqueue)
void enqueue(int item) {
if (isFull()) {
cout << "Queue Overflow\n";
return;
}
rearIdx = (rearIdx + 1) % capacity; // Circular increment rear index
arr[rearIdx] = item;
size++;
}
// Function to remove an element from the front of the queue (dequeue)
int dequeue() {
if (isEmpty()) {
cout << "Queue Underflow\n";
return -1;
}
int frontElement = arr[frontIdx];
frontIdx = (frontIdx + 1) % capacity; // Circular increment front index
size--;
return frontElement;
}
// Function to get the front element of the queue
int front() {
if (isEmpty()) {
cout << "Queue is empty\n";
return -1;
}
return arr[frontIdx];
}
// Function to check if the queue is empty
bool isEmpty() {
return size == 0;
}
// Function to check if the queue is full
bool isFull() {
return size == capacity;
}
// Function to get the size of the queue
int getSize() {
return size;
}
};
int main() {
Queue queue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
cout << "Front element: " << queue.front() << endl;
queue.dequeue();
cout << "Front element after dequeue: " << queue.front() << endl;
cout<<queue.getSize();
cout<<endl;
cout<<queue.isFull();
cout<<endl;
return 0;
}