Program to implement Queue using Linked List C++

Today we are going to write a program to implement queue using linked list C++, let’s start with what is queue:

 

What is QUEUE?

implement queue using linked list C++

 

 

A Queue is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data structure.

 

Program to implement Queue using Linked List C++

#include<iostream>
using namespace std;

struct node
{
    int data;
    node *next;
}*front = NULL,*rear = NULL,*p = NULL,*np = NULL;

void push(int x)
{
    np = new node;
    np->data = x;
    np->next = NULL;
    if(front == NULL)
    {
        front = rear = np;
        rear->next = NULL;
    }
    else
    {
        rear->next = np;
        rear = np;
        rear->next = NULL;
    }
}
int remove()
{
    int x;
    if(front == NULL)
    {
        cout<<"empty queuen";
    }
    else
    {
        p = front;
        x = p->data;
        front = front->next;
        delete(p);
        return(x);
    }
}
int main()
{
    int n,c = 0,x;
    cout<<"Enter the number of values to be pushed into queuen";
    cin>>n;
    while (c < n)
    {
    cout<<"Enter the value to be entered into queuen";
    cin>>x;
        push(x);
        c++;
     }
     cout<<"nnRemoved Valuesnn";
     while(true)
     {
        if (front != NULL)
            cout<<remove()<<endl;
        else
            break;
     }
     return 0;
}

 

OUTPUT:

Enter the number of values to be pushed into queue
5
Enter the value to be entered into queue
5
Enter the value to be entered into queue
3
Enter the value to be entered into queue
2
Enter the value to be entered into queue
9
Enter the value to be entered into queue
1


Removed Values

5
3
2
9
1

--------------------------------
Process exited after 16.89 seconds with return value 0
Press any key to continue . . .

 

2 thoughts on “Program to implement Queue using Linked List C++”

  1. why do we want to mention the rear->next=NULL

    as we create the node new we are mentioning it np->next=NULL
    if we do rear=np automatically it forms rear->next =NULL

    as a result rear->next=NULL is not required

    Reply

Leave a Reply to Melwin Cancel reply