How to implement queue using Linked list in C++

In this tutorial, we will learn how to implement a Queue using a linked list in the C++ programming language.

queue implementation using linked list in C++

A queue is a form of a data structure that follows the FIFO(first in first out) concept i.e in case of a queue the element which we will insert first, then the same will get deleted first.

In a queue, implementation elements we insert elements from the rear end, and the elements will be removed from the front. We can imagine a queue as a container adapter that holds data of equivalent datatype.

1. Enqueue: inserting an element at the rear end of the queue.

2. Dequeue: remove an element from the front of the queue.

#include<iostream>

using namespace std;

struct Node
{
    int data;
    Node *next ;
};
class Queue
{
    Node *front, *rear;

public:
    Queue()
    {
        front = rear = NULL;  //   Initially

    }
    void Enqueue(int elem)    // for insertion from rear
    {
        Node *newnode;
        newnode = new Node;
        newnode->data = elem;
        newnode->next = NULL;

        if(front == NULL)
            front = rear = newnode;
        else
        {
            rear->next = newnode;
            rear = newnode;
        }
    }
    void Dequeue()            // for deletion from front
    {
        Node *temp;
        if(front == NULL)
            cout<<"Queue is Empty";
        else
        {
            temp= front;
            front = front->next;
            delete temp;
        }

    }
    void display()
    {
        Node *temp;
        temp= front;
        while(temp!=NULL) // (temp!= rear->next)
        {
            cout<<temp->data<<"\t";
            temp = temp->next;
        }
        cout<<endl;
    }
};
int main()

{
    Queue Q1;
    Q1.Enqueue(10);
    cout<<"Queue after First Enqueue :";
    Q1.display();
    cout<<"\n";
    Q1.Enqueue(20);
    cout<<"Queue after Second Enqueue :";
    Q1.display();
    cout<<"\n";
    Q1.Dequeue();
    cout<<"Queue after Dequeue :";
    Q1.display();
}


OUTPUT:

Queue after first Enqueue: 10

Queue after Second Enqueue: 10 20

Queue after Dequeue: 20

 

You may also like to visit:

Leave a Reply

Your email address will not be published. Required fields are marked *