Site icon T4Tutorials.com

Program to Implement Priority Queue in Data Structures (C plus plus)

Program to Implement Priority Queue in Data Structures (C plus plus)

In this tutorial, we will learn about the Program to Implement Priority Queue in Data Structures (C plus plus).

/*C++ Program to Implement Priority Queue*/

#include <iostream>
#include <cstdlib>

using namespace std;
 
/*Declaring the node*/

struct node
{
	int prior;
	int data;
	struct node *link;
};

class priority_queue
{
    private:
        node *front;
    public:
        priority_queue()
        {
             front = NULL;
        }
        

        void insertion(int item, int prior)
        {
            node *tmp, *q;
            tmp = new node;
            tmp->data = item;
            tmp->prior = prior;
            if (front == NULL || prior < front->prior)
            {
                tmp->link = front;
                front = tmp;
            }
            
            else
            {
                q = front;
                while (q->link != NULL && q->link->prior <= prior)
                    q=q->link;
                tmp->link = q->link;
                q->link = tmp;
            }
        }
        

        void deletion()
        {
            node *tmp;
            if(front == NULL)
                cout<<"Queue Underflowed "<<endl;
                
            else
            {
                tmp = front;
                cout<<"Deleted value is: "<<tmp->data<<endl;
                front = front->link;
                free(tmp);
            }
        }

        void show()
        {
            node *ptr;
            ptr = front;
            if (front == NULL)
                cout<<"Empty Queue "<<endl;
                
            else
            {	cout<<"Queue is: "<<endl;
                cout<<"Priority       Value "<<endl;
                while(ptr != NULL)
                {
                    cout<<ptr->prior<<"                 "<<ptr->data<<endl;
                    ptr = ptr->link;
                }
            }
        }
};

int main()
{
    int ch, val, prior;
    priority_queue pq; 
    do
    {
        cout<<"1. Insertion "<<endl;
        cout<<"2. Deletion "<<endl;
        cout<<"3. Display "<<endl;
        cout<<"4. Exit "<<endl;
        cout<<"Please enter your choice : "; 
        cin>>ch;
        
        switch(ch)
        {
        case 1:
             cout<<"Please enter the value to be added in the queue : ";
            cin>>val;
            cout<<"Please enter its priority : ";
            cin>>prior;
            pq.insertion(val, prior);
            break;
        case 2:
            pq.deletion();
            break;
        case 3:
            pq.show();
            break;
        case 4:
            break;
        default :
            cout<<"Invalid entry"<<endl;
        }
    }
    while(ch != 4);
    return 0;
}

Output:

Program to Implement Priority Queue in Data Structures (C plus plus)
Exit mobile version