#include <iostream>
using namespace std;
// Node structure for the linked list
struct Node {
int data;
Node* next;
};
// Global pointers to manage the queue
Node* front = NULL; // Points to the front of the queue
Node* rear = NULL; // Points to the rear of the queue
// Enqueue function to add an element to the queue
void enqueue(int value) {
Node* new_node = new Node();
new_node->data = value;
new_node->next = NULL;
if (rear == NULL) { // If the queue is empty
front = rear = new_node;
cout << value << " added to the queue.\n";
return;
}
rear->next = new_node; // Add new node at the end
rear = new_node; // Update rear to the new node
cout << value << " added to the queue.\n";
}
// Dequeue function to remove an element from the queue
void dequeue() {
if (front == NULL) { // If the queue is empty
cout << "Queue underflow! No elements to remove.\n";
return;
}
Node* temp = front; // Store the current front
front = front->next; // Move front to the next node
if (front == NULL) { // If the queue becomes empty
rear = NULL;
}
cout << temp->data << " removed from the queue.\n";
delete temp; // Free memory of the removed node
}
// Display function to show the elements in the queue
void display() {
if (front == NULL) {
cout << "The queue is empty.\n";
return;
}
Node* temp = front;
cout << "Queue elements: ";
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Main function to test the queue implementation
int main() {
int choice, value;
do {
cout << "\nQueue Menu:\n";
cout << "1. Enqueue (Insert)\n";
cout << "2. Dequeue (Remove)\n";
cout << "3. Display Queue\n";
cout << "0. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the value to enqueue: ";
cin >> value;
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 0:
cout << "Exiting the program.\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 0);
return 0;
}