---- 22 Circular queue
//---- By Base Method
#include <iostream>
class CircularQueue
{
private:
int *arr;
int capacity; // Maximum number of elements
int front; // Index of front element
int rear; // Index of rear element
public:
CircularQueue(int size)
{
capacity = size;
arr = new int[capacity];
front = rear = -1; // Initially queue is empty
}
// Check if queue is full
bool isFull()
{
return (rear + 1) % capacity == front;
}
// Check if queue is empty
bool isEmpty() {
return front == -1;
}
// Enqueue an element
void enqueue(int data)
{
if (isFull())
{
std::cout << "Queue overflow\n";
return;
}
if (front == -1)
{
front = 0; // If queue was empty, set front to 0
}
rear = (rear + 1) % capacity; // Update rear circularly
arr[rear] = data;
}
// Dequeue an element
int dequeue() {
if (isEmpty())
{
std::cout << "Queue underflow\n";
return -1;
}
int data = arr[front];
if (front == rear)
{
// If only one element, reset front and rear
front = rear = -1;
} else
{
front = (front + 1) % capacity; // Update front circularly
}
return data;
}
// Display the queue
void display() {
if (isEmpty()) {
std::cout << "Queue is empty\n";
return;
}
std::cout << "Queue elements: ";
for (int i = front; i != rear; i = (i + 1) % capacity) {
std::cout << arr[i] << " ";
}
// Handle the case when rear is before front (circular)
if (front > rear) {
for (int i = 0; i <= rear; i++) {
std::cout << arr[i] << " ";
}
}
std::cout << "\n";
}
};
int main() {
CircularQueue q(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display(); // Output: Queue elements: 10 20 30
q.dequeue();
q.display(); // Output: Queue elements: 20 30
return 0;
}
//---- By SDL
#include <iostream>
#include <queue>
template <typename T, size_t MaxSize>
class CircularQueue
{
private:
std::queue<T> q;
size_t currentSize;
public:
CircularQueue() : currentSize(0) {}
// Function to enqueue an element
void enqueue(const T& element) {
if (currentSize == MaxSize) {
std::cout << "Queue is full. Cannot enqueue." << std::endl;
return;
}
q.push(element);
currentSize++;
}
// Function to dequeue an element
void dequeue() {
if (currentSize == 0) {
std::cout << "Queue is empty. Cannot dequeue." << std::endl;
return;
}
q.pop();
currentSize--;
}
// Function to display the queue
void display() {
if (currentSize == 0) {
std::cout << "Queue is empty." << std::endl;
return;
}
std::cout << "Queue elements: ";
std::queue<T> temp = q;
while (!temp.empty()) {
std::cout << temp.front() << " ";
temp.pop();
}
std::cout << std::endl;
}
};
int main() {
// Create a circular queue of integers with maximum size 5
CircularQueue<int, 5> cq;
cq.enqueue(1);
cq.enqueue(2);
cq.enqueue(3);
cq.enqueue(4);
cq.enqueue(5); // Queue is full after this
cq.display();
cq.dequeue();
cq.dequeue();
cq.enqueue(6); // Now there's space again
cq.display();
return 0;
}
No comments:
Post a Comment
Fell free to write your query in comment. Your Comments will be fully encouraged.