0% found this document useful (0 votes)
15 views3 pages

Queue Codeszzzzz

The document contains a C++ implementation of a Queue data structure using a linked list. It includes methods for enqueueing, dequeueing, printing the queue, and displaying the front element. The main function provides a user interface for performing these operations interactively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Queue Codeszzzzz

The document contains a C++ implementation of a Queue data structure using a linked list. It includes methods for enqueueing, dequeueing, printing the queue, and displaying the front element. The main function provides a user interface for performing these operations interactively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

using namespace std;

class Node {
public:
int data;
Node* next;
};

class Queue {
private:
Node* front;
Node* rear;

public:
Queue() {
front = rear = nullptr;
}

void enqueue(int value) {


Node* newNode = new Node;
newNode->data = value;
newNode->next = nullptr;

if (rear == nullptr) {
front = rear = newNode;
return;
}

rear->next = newNode;
rear = newNode;
}

void dequeue() {
if (front == nullptr) {
cout << "\tQueue is empty. Unable to dequeue." << endl;
return;
}

Node* temp = front;


front = front->next;

if (front == nullptr) {
rear = nullptr;
}

delete temp;
}

void printFront() {
if (front == nullptr) {
cout << "\tQueue is empty" << endl;
} else {
cout << "\tFront element = " << front->data << endl;
}
}

void printQueue() {
if (front == nullptr) {
cout << "\tQueue is empty" << endl;
return;
}

Node* current = front;


cout << "\tQueue elements: ";
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}

~Queue() {
while (front != nullptr) {
Node* temp = front;
front = front->next;
delete temp;
}
rear = nullptr;
}
};

int main() {
Queue queue;
int op, data;

do {
cout << "\nChoose an operation to perform:\n\t";
cout << "[1] Enqueue a node into the queue\n\t";
cout << "[2] Dequeue a node from the queue\n\t";
cout << "[3] Display the queue\n\t";
cout << "[4] Display the front element of the queue\n\t";
cout << "[5] Exit program\n\n\tInput option: ";
cin >> op;

switch (op) {
case 1:
cout << "\tEnter data: ";
cin >> data;
queue.enqueue(data);
break;
case 2:
queue.dequeue();
break;
case 3:
queue.printQueue();
break;
case 4:
queue.printFront();
break;
case 5:
return 0;
default:
cout << "\tInvalid choice!" << endl;
break;
}
} while (true);

return 0;
}

You might also like