Answer to Question #273410 in C++ for zain

Question #273410

priority Queues

modify the class queues so that it now behaves as a priority queue. A priority queue is a queue whose enqueue function is different in such a way that if a node has a priority value higher than the one already in the queue, it rearranges so that now the higher priority node is before the lower priority node in the queue.


we shall make a priority queue of a shopping list. the shopping list is defined by a dynamic collection of nodes containing itemName and isleNo. the list is prioritized according to isleNo. in any shopping mart, the isle numbers are arranged in ascending order. a mart can only have 20 isles at maximum.


1
Expert's answer
2021-11-30T00:36:43-0500
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
	int data;
	int priority;


	struct node* next;


} Node;
Node* newNode(int d, int p)
{
	Node* temp = (Node*)malloc(sizeof(Node));
	temp->data = d;
	temp->priority = p;
	temp->next = NULL;


	return temp;
}
int peek(Node** h)
{
	return (*h)->data;
}
void pop(Node** h)
{
	Node* temp = *h;
	(*h) = (*h)->next;
	free(temp);
}
void push(Node** h, int d, int pr)
{
	Node* srt = (*h);
	Node* temp = newNode(d, pr);
	if ((*h)->priority > pr)
	{
		temp->next = *h;
		(*h) = temp;
	}
	else
		while (srt->next != NULL &&
			srt->next->priority < pr)
		{
			srt = srt->next;
		}
		temp->next = srt->next;
		srt->next = temp;
	
}


int isEmpty(Node** h)
{
	return (*h) == NULL;
}


int main()
{
	Node* p = newNode(10, 1);
	push(&p, 11, 2);
	push(&p, 12, 3);
	push(&p, 13, 0);


	while (!isEmpty(&p))
	{
		cout << " " << peek(&p);
		pop(&p);
	}
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS