22. DSA with C++ - Queue using Linked List

Queue using Linked List

This is an implementaon of a queue using a linked list in C++. It includes the basic operaons of a queue such as enqueue, dequeue, peek, isEmpty, and display:

Queue using Linked List

Implementation of a queue using a linked list in C++:

#include <iostream>

struct Node {
    int data;
    Node* next;
};

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

public:
    Queue() : front(nullptr), rear(nullptr) {}

    ~Queue() {
        while (!isEmpty()) {
            dequeue();
        }
    }

    bool isEmpty() {
        return front == nullptr;
    }

    void enqueue(int value) {
        Node* newNode = new Node;
        newNode->data = value;
        newNode->next = nullptr;

        if (isEmpty()) {
            front = rear = newNode;
        } else {
            rear->next = newNode;
            rear = newNode;
        }
        std::cout << "Enqueued: " << value << std::endl;
    }

    void dequeue() {
        if (isEmpty()) {
            std::cout << "Queue is empty. Unable to dequeue." << std::endl;
            return;
        }
        Node* temp = front;
        front = front->next;
        std::cout << "Dequeued: " << temp->data << std::endl;
        delete temp;
        if (isEmpty()) {
            rear = nullptr;
        }
    }

    int peek() {
        if (isEmpty()) {
            std::cout << "Queue is empty." << std::endl;
            return -1;
        }
        return front->data;
    }

    void display() {
        if (isEmpty()) {
            std::cout << "Queue is empty." << std::endl;
            return;
        }
        Node* temp = front;
        std::cout << "Queue: ";
        while (temp != nullptr) {
            std::cout << temp->data << " ";
            temp = temp->next;
        }
        std::cout << std::endl;
    }
};

int main() {
    Queue queue;
    queue.enqueue(10);
    queue.enqueue(20);
    queue.enqueue(30);
    queue.enqueue(40);
    queue.display(); // Queue: 10 20 30 40
    queue.dequeue();
    queue.dequeue();
    queue.display(); // Queue: 30 40
    std::cout << "Front of the queue: " << queue.peek() << std::endl; // Front of the queue: 30
    return 0;

            

The Queue class provides the following operaons:
  • enqueue(int value): Inserts an element at the rear of the queue.
  • dequeue(): Removes the element from the front of the queue.
  • isEmpty(): Checks if the queue is empty.
  • peek(): Returns the front element of the queue without removing it.
  • display(): Displays all the elements in the queue.
  • In the main funcon, we create a queue object and perform various operaons such as enqueueing elements, dequeueing elements, peeking the front element, and displaying the contents of the queue.
Output }


Enqueued: 10 
Enqueued: 20 
Enqueued: 30 
Enqueued: 40 
Queue: 10 20 30 40 
Dequeued: 10 
Dequeued: 20 
Queue: 30 40 
Front of the queue: 30