0% found this document useful (0 votes)
3 views4 pages

LL Based Queue

Uploaded by

zuhaahsan014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

LL Based Queue

Uploaded by

zuhaahsan014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

// Node structure for the linked list

struct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Queue class using a linked list

class Queue {

private:

Node* front; // Points to the front of the queue

Node* rear; // Points to the rear of the queue

public:

// Constructor

Queue() {

front = rear = nullptr;

// Enqueue: Insert an element at the rear

void enqueue(int value) {

Node* newNode = new Node(value);


if (rear == nullptr) { // Empty queue

front = rear = newNode;

cout << value << " enqueued to queue\n";

return;

rear->next = newNode;

rear = newNode;

cout << value << " enqueued to queue\n";

// Dequeue: Remove an element from the front

void dequeue() {

if (isEmpty()) {

cout << "Queue Underflow! Cannot dequeue.\n";

return;

Node* temp = front;

cout << front->data << " dequeued from queue\n";

front = front->next;

// If queue becomes empty after dequeue

if (front == nullptr) {

rear = nullptr;

delete temp;

}
// Peek: View the front element

int peek() {

if (isEmpty()) {

cout << "Queue is empty.\n";

return -1;

return front->data;

// Check if the queue is empty

bool isEmpty() {

return front == nullptr;

// Display all elements in the queue

void display() {

if (isEmpty()) {

cout << "Queue is empty.\n";

return;

Node* temp = front;

cout << "Queue elements (front to rear): ";

while (temp != nullptr) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

}
// Destructor to clean up memory

~Queue() {

while (!isEmpty()) {

dequeue();

};

// Driver code

int main() {

Queue q;

[Link](10);

[Link](20);

[Link](30);

[Link]();

cout << "Front element is: " << [Link]() << endl;

[Link]();

[Link]();

return 0;

You might also like