Queue using ArrayList in C++
This is an implementaon of a queue using dynamic arrays in C++, including all the basic operaons: enqueue, dequeue, isEmpty, isFull, and display.
#include <iostream>
class Queue {
private:
int* arr; // Dynamic array to store queue elements
int front; // Index of the front element
int rear; // Index of the rear element
int capacity; // Maximum capacity of the queue
int size; // Current size of the queue
public:
// Constructor
Queue(int capacity) {
this->capacity = capacity;
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
// Destructor
~Queue() {
delete[] arr;
}
// 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 add an element to the rear of the queue (enqueue operation)
void enqueue(int element) {
if (isFull()) {
std::cout << "Queue is full. Cannot enqueue element: " << element << std::endl;
return;
}
rear = (rear + 1) % capacity;
arr[rear] = element;
size++;
}
// Function to remove an element from the front of the queue (dequeue operation)
void dequeue() {
if (isEmpty()) {
std::cout << "Queue is empty. Cannot dequeue element." << std::endl;
return;
}
int removedElement = arr[front];
front = (front + 1) % capacity;
size--;
std::cout << "Dequeued element: " << removedElement << std::endl;
}
// Function to display the elements in the queue
void display() {
if (isEmpty()) {
std::cout << "Queue is empty. No elements to display." << std::endl;
return;
}
std::cout << "Queue elements: ";
int count = 0;
int i = front;
while (count < size) {
std::cout << arr[i] << " ";
i = (i + 1) % capacity;
count++;
}
std::cout << std::endl;
}
};
int main() {
int capacity = 5;
Queue queue(capacity);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60); // Queue is full, cannot enqueue element 60
queue.display();
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.display();
return 0;
}
Explanation:
- The Queue class represents the dynamic array-based queue.
- The constructor ini alizes the dynamic array, front, rear, capacity, and size.
- The destructor frees the memory allocated for the dynamic array.
- The isEmpty funcon checks if the queue is empty.
- The isFull funcon checks if the queue is full.
- The enqueue funcon adds an element to the rear of the queue.
- - The dequeue funcon removes an element from the front of the queue.
- The display funcon prints the elements in the queue.
- In the main funcon, we create a queue object, enqueue elements, dequeue elements, and display the elements in the queue.
Queue elements: 10 20 30 40 50
Dequeued element: 10
Dequeued element: 20
Dequeued element: 30
Queue elements: 40 50