Priority Queue
#include <iostream>
using namespace std;
struct Node{ //defining node template
int info;
int pn;
Node *next;
};
Node *front = NULL;
Node *rear = NULL;
void insertQ()
{ Node * mid, *temp, *prev;
//mid=prev=front;
temp = new Node; // create a new node named temp
/*Take the value of the new node from user */
cout << "Enter the value of the node that u want to insert : \n";
cin>>temp->info; // value assigned
cout << "Enter the priority of the node that u want to insert : \n";
cin>>temp->pn; // priority assigned
temp->next = NULL; // next assigned to NULL
/* case1, if the list is empty*/
if(front== NULL) // List empty, inserted item is the 1st one
{front = temp;
rear= temp;
}
else{
mid = front;
prev=mid;
while( (mid!=NULL) && (mid->pn <= temp->pn)){
prev= mid;
mid= mid->next;
}
temp->next= prev->next;
prev->next=temp;
} /* Else part is for --List non empty*/
}
void showQ()
{
Node *mid; // take a temporary poiter to travrse the list
cout << "Showing the list:\n";
mid = front; // start from begining ( front)
if(front==NULL) // check if the list is empty
cout<<"List is empty\n";
while (mid!=NULL) // List is not epty, now print the list until u get NULL
{cout << mid->info<< "-";
cout << mid->pn<< " -->";
mid = mid->next;
}
cout<<endl;
}
void deleteQ()
{ Node * temp;
if(front==NULL) // first check if the list is empty
cout<<"List is empty\n";
else
{ temp = front;
cout<<"Dleted item is :\n"<< temp->info<<endl;
front=front->next; // DElete one node from front
delete(temp); // free the deleted node
}
}
int main()
{
int i, option;
Node *temp;
Node *mid;
do{
cout<<"1. Insert in Q \n";
cout<<"2. Delete from Q \n";
cout<<"3. Show Q \n";
cout<<"4. Exit \n";
cout<<"Enter which option you want(1-4): \n";
cin>> option;
switch(option)
{
case 1: insertQ(); // calling createlist function
break;
case 2: deleteQ();
break;
case 3: showQ();
}
}while(option!=4);
system("pause");
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment