In: Computer Science
write a java program to Implement a Priority Queue using a linked list. Include a main method demonstrating enqueuing and dequeuing several numbers, printing the list contents for each.
import java.util.* ;
public class Priority_Queue{
// java program to implement Priority_Queue
// using Linked_List
// Node
static class Node {
int data;
// Lower the values indicates the higher
priority
int priority;
Node next;
}
static Node node = new Node();
// function to create A New_Node
static Node newNode(int d, int p)
{
Node temp = new Node();
temp.data = d;
temp.priority = p;
temp.next = null;
return temp;
}
// returns the value at head
static int peek(Node head)
{
return (head).data;
}
// function to remove node according to priority
static Node Dequeue(Node head)
{
Node temp = head;
(head) = (head).next;
return head;
}
// function to insert node according to priority
static Node Enqueue(Node head, int d, int
p)
{
Node start = (head);
// Create new Node
Node temp = newNode(d, p);
// Rare case: The head of list has lesser
// priority than new node. So insert new
// node before head node and change head
node.
if ((head).priority > p) {
// insert New_Node
before head
temp.next = head;
(head) = temp;
}
else {
// Traverse the list and
find a
// position to insert
new node
while (start.next !=
null &&
start.next.priority < p) {
start = start.next;
}
// Either at the ends of
the list
// or at required
position
temp.next =
start.next;
start.next = temp;
}
return head;
}
// Function to check is list is empty
static int isEmpty(Node head)
{
return ((head) == null)?1:0;
}
//Main Function
public static void main(String []args){
Node pq = newNode(4, 1);
// Enqueue operations
pq =Enqueue(pq, 5, 2);
pq =Enqueue(pq, 6, 3);
pq =Enqueue(pq,23424,5);
pq =Enqueue(pq, 7, 0);
// functions dequeue's the priority_queue until
its empty
while (isEmpty(pq)==0) {
System.out.printf("%d ",
peek(pq));
//Dequeue
operations
pq=Dequeue(pq);
}
}
}
---------summary--------
what does main function do?
1.Creates a new node first for priority queue .
2.Performs some Enqueue operations.
3.Dequeue's the Priority queue until it's empty.
4.Print's the value of highest priority while dequeueing the queue.