Home » Code snippets » C/C++ Code Snippets

C++ - Implementation of Queue using Linked List.

In this code snippet we will learn how to implement Queue using Linked List in c++ programming language?

In this example we will implement Queue using Linked List with Insert, Display and Delete item operation with C++ class.

C++ Code Snippet - Implement Queue using Linked List

//Implementation of Queue using Linked List

#include<iostream>
 
using namespace std;
 
struct Node{
    int data;
    Node *next;
};
 
class Queue{
    public:
    Node *front,*rear;
    Queue(){front=rear=NULL;}
 
    void insert(int n);
    void deleteitem();
    void display();
    ~Queue();
};
 
void Queue::insert(int n){
    Node *temp=new Node;
    if(temp==NULL){
        cout<<"Overflow"<<endl;
        return;
    }
    temp->data=n;
    temp->next=NULL;
 
    //for first node
    if(front==NULL){
        front=rear=temp;
    }
    else{
        rear->next=temp;
        rear=temp;
    }
    cout<<n<<" has been inserted successfully."<<endl;
}
 
void Queue::display(){
    if(front==NULL){
        cout<<"Underflow."<<endl;
        return;
    }
    Node *temp=front;
    //will check until NULL is not found
    while(temp){
        cout<<temp->data<<" ";
        temp=temp->next;
    }
    cout<<endl;
}
 
void Queue :: deleteitem()
    {
    if (front==NULL){
        cout<<"underflow"<<endl;
        return;
    }
     
    cout<<front->data<<" is being deleted "<<endl;
    if(front==rear)//if only one node is there
        front=rear=NULL;
    else
        front=front->next;
}
 
Queue ::~Queue()
{
    while(front!=NULL)
    {
        Node *temp=front;
        front=front->next;
        delete temp;
    }
    rear=NULL;
}
 
 
int main(){
    Queue Q;
    Q.display();
 
    Q.insert(10);
    Q.insert(24);
    Q.insert(28);
    Q.insert(32);
    Q.insert(30);
     
    Q.display();
     
    Q.deleteitem();
    Q.deleteitem();
    Q.deleteitem();
    Q.deleteitem();
    Q.deleteitem();
     
    return 0;
}

Output

    Underflow.
    10 has been inserted successfully.
    24 has been inserted successfully.
    28 has been inserted successfully.
    32 has been inserted successfully.
    30 has been inserted successfully.
    10 24 28 32 30
    10 is being deleted 
    24 is being deleted 
    28 is being deleted 
    32 is being deleted 
    30 is being deleted


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.