Priority - Queue Using DLL
Priority - Queue Using DLL
*;
class Main {
// **Node Class**
// Represents each element in the priority queue
static class Node {
int data; // Value of the node
int priority; // Priority of the node
Node next, prev; // Pointers for doubly linked list
/**
* **Push Method**
* Inserts a new node in the queue based on its priority.
* @param data Value of the new node
* @param priority Priority of the new node
*/
private static void push(int data, int priority) {
// Case 1: If the queue is empty, make the new node the head
if (head == null) {
Node newNode = new Node(data, priority);
head = newNode;
return;
}
/**
* **Peek Method**
* Returns the value of the highest priority element without removing it.
* @return The data of the head node, or -1 if the queue is empty.
*/
private static int peek() {
if (head != null) {
return head.data; // Return the value of the head node
}
return -1; // If queue is empty
}
/**
* **Pop Method**
* Removes and returns the highest priority element from the queue.
* @return The data of the head node, or -1 if the queue is empty.
*/
private static int pop() {
if (head != null) {
int curr = head.data; // Store the value of the head node
head = head.next; // Move the head to the next node
if (head != null) {
head.prev = null; // Update the backward link
}
return curr; // Return the removed node's value
}
return -1; // If queue is empty
}
/**
* **Main Method**
* Demonstrates priority queue functionality with an example.
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
5
10 3
20 1
30 4
40 2
50 3