FULL QUEUE IMPLEMENTATION THROGH ARRAY !!!!!!!!!
Sun Nov 24 2024 23:20:17 GMT+0000 (Coordinated Universal Time)
Saved by @E23CSEU1151
#include <iostream> using namespace std; class Queue { public: int *arr; // Pointer for dynamically allocated array int front; // Index of the front element int rear; // Index of the rear element int size; // Maximum size of the queue // Constructor to initialize the queue Queue(int size) { this->size = size; arr = new int[size]; front = 0; // Initially, front is 0 rear = 0; // Initially, rear is 0 } // Enqueue: Add an element to the rear of the queue void enqueue(int element) { // Check if the queue is full if (rear == size) { cout << "Queue is full (Overflow)" << endl; } else { arr[rear] = element; // Add element at the rear rear++; // Increment the rear index cout << element << " added to the queue" << endl; } } // Dequeue: Remove an element from the front of the queue void dequeue() { // Check if the queue is empty if (front == rear) { cout << "Queue is empty (Underflow)" << endl; } else { cout << arr[front] << " removed from the queue" << endl; front++; // Increment the front index to the next element } } // isEmpty: Check if the queue is empty bool isEmpty() { return front == rear; } // Front: Retrieve the front element without removing it int getFront() { if (isEmpty()) { cout << "Queue is empty (No front element)" << endl; return -1; // Return an invalid value as the queue is empty } else { return arr[front]; // Return the front element } } }; int main() { // Create a queue of size 5 Queue q(5); // Enqueue elements q.enqueue(10); q.enqueue(20); q.enqueue(30); // Display the front element cout << "Front element: " << q.getFront() << endl; // Dequeue elements q.dequeue(); cout << "Front element after dequeue: " << q.getFront() << endl; // Check if the queue is empty if (q.isEmpty()) { cout << "The queue is empty" << endl; } else { cout << "The queue is not empty" << endl; } return 0; }
Comments