Question: The unit test for remove() on empty queue is not working correctly. Program in C++. Code is already provided. Implement a Priority Queue for strings.
The unit test for "remove() on empty queue" is not working correctly.
Program in C++. Code is already provided.
Implement a Priority Queue for strings. A priority queue is similar to a regular queue except each item added to the queue also has an associated priority. For this problem, make the priority an integer where 0 is the highest priority and larger values are increasingly lower in priority.
The remove function should return and remove the item that has the highest priority. For example:
q.add(X, 10); q.add(Y, 1); q.add(Z, 3); cout << q.remove(); // Returns Y cout << q.remove(); // Returns Z cout << q.remove(); // Returns X
You can implement the priority queue by performing a linear search in the remove() function.
You are expected to use pointers. You will get a 0 if you use STL::priorityqueue or any other already-implemented priority queue data structure.
Important: Make sure to use the template provided since the test cases depend on it.
#include #include #include #include #include using namespace std;
class Node // definition of node class { public: Node() { data =" "; priority = 0; }
void setData(string s) { data = s; } void setPriority(int p) { priority = p; } string getData() { return data; } int getPriority() { return priority; } Node * getLink() { return link; } void setLink(Node *l) { link = l; } private: string data; int priority; Node *link; }; class PriorityQueue { public: PriorityQueue() { front = NULL; } void add(string item, int priority) { Node *tmp, *q; tmp = new Node; tmp->setData(item); tmp->setPriority(priority); if (front == NULL || priority < front->getPriority()) { tmp->setLink(front); front = tmp; } else { q = front; while (q->getLink() != NULL && q->getLink()->getPriority() <= priority) q=q->getLink(); tmp->setLink(q->getLink()); q->setLink(tmp); } } string remove() { Node *tmp; if(front == NULL) cout; else { string s; tmp = front; s = tmp->getData(); front = front->getLink(); free(tmp); return s; } } void display() { Node *ptr; ptr = front; if (front == NULL) cout<<"Queue is empty "; else { cout<<"Queue is : "; cout<<"Priority Item "; while(ptr != NULL) { cout
}; int main() { int choice, priority; string data; PriorityQueue pq; do { cout<<"1.Insert "; cout<<"2.Delete "; cout<<"3.Display "; cout<<"4.Quit "; cout<<"Enter your choice : "; cin>>choice; switch(choice) { case 1: cout<<"Input the item value to be added in the queue : "; cin>>data; cout<<"Enter its priority : "; cin>>priority; pq.add(data, priority); break; case 2: cout << pq.remove(); break; case 3: pq.display(); break; case 4: break; default : cout<<"Wrong choice "; } } while(choice != 4); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
