Let a linked list consists of n number of nodes, where each node consists of a unique
number, a priority number (in between 1 to 5), and pointer to next node. Design the
algorithm/develop pseudocode to divide the nodes into different linked list where
each linked consists of nodes having same priority.
#include <bits/stdc++.h>
using namespace std;
struct List
{
int uniqueNumber;
int priorityNumber;
struct List* nextNode;
};
List* new_node(int data, int priority)
{
List* tempNode = (List*)malloc(sizeof(List));
tempNode->uniqueNumber = data;
tempNode->priorityNumber = priority;
tempNode->nextNode = NULL;
return tempNode;
}
int removingFront(List** node)
{
return (*node)->uniqueNumber;
}
void popElement(List** node)
{
List* tempNode = *node;
(*node) = (*node)->nextNode;
free(tempNode);
}
void pushElement(List** node, int data, int priority)
{
List* startNode= (*node);
List* tempNode = new_node(data, priority);
if ((*node)->priorityNumber > priority)
{
tempNode->nextNode = *node;
(*node) = tempNode;
}
else
{
while (startNode->nextNode != NULL &&
startNode->nextNode->priorityNumber < priority)
{
startNode = startNode->nextNode;
}
tempNode->nextNode = startNode->nextNode;
startNode->nextNode = tempNode;
}
}
int isEmpty(List** node)
{
return (*node) == NULL;
}
// Testing code
int main()
{
// Create a linked list
List* pq = new_node(4, 1);
pushElement(&pq, 5, 2);
pushElement(&pq, 6, 3);
pushElement(&pq, 7, 0);
while (!isEmpty(&pq))
{
cout << " " << removingFront(&pq);
popElement(&pq);
}
return 0;
}
Comments
Leave a comment