Implement queue data structure and its operations using arrays.
Implement queue data structure and its operations using arrays.
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Queue {
private:
int front; // Index of the front element in the queue
int rear; // Index of the rear element in the queue
int arr[MAX_SIZE]; // Array to store the queue elements
public:
Queue() {
front = -1; // Initialize front to -1 to indicate an empty queue
rear = -1; // Initialize rear to -1 to indicate an empty queue
}
bool isEmpty() {
return (front == -1);
}
bool isFull() {
return ((rear + 1) % MAX_SIZE == front);
}
void enqueue(int value) {
if (isFull()) {
cout << "Queue Overflow: Cannot enqueue element " << value << ". Queue is full." << endl;
return;
}
if (isEmpty()) {
front = 0; // If the queue is empty, update front to 0
}
rear = (rear + 1) % MAX_SIZE;
arr[rear] = value;
cout << "Enqueued element: " << value << endl;
}
void dequeue() {
if (isEmpty()) {
cout << "Queue Underflow: Cannot dequeue element. Queue is empty." << endl;
return;
}
int dequeuedElement = arr[front];
if (front == rear) {
front = -1; // If there was only one element in the queue, reset front and rear to -1
rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
cout << "Dequeued element: " << dequeuedElement << endl;
}
int peek() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return -1;
}
return arr[front];
}
void display() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
cout << "Queue elements: ";
int i = front;
while (i != rear) {
cout << arr[i] << " ";
i = (i + 1) % MAX_SIZE;
}
cout << arr[i] << endl;
}
};
int main() {
Queue queue;
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.display();
cout << "Front element: " << queue.peek() << endl;
queue.dequeue();
queue.display();
queue.dequeue();
queue.dequeue();
queue.display();
return 0;
}
Comments
Post a Comment