How do i program a Priority Queue with Nodes in Java?
- User
How do i program a Priority Queue with Nodes in Java?
- Assistant
How do i program a Priority Queue with Nodes in Java?
A priority queue with nodes can be implemented in Java using a Binary Heap (Min-Heap or Max-Heap). Here's a simple example of a Min-Heap priority queue with nodes in Java:
import java.util.ArrayList;
import java.util.List;
class Node {
int key;
String value;
public Node(int key, String value) {
this.key = key;
this.value = value;
}
}
public class PriorityQueue {
private List<Node> heap;
public PriorityQueue() {
heap = new ArrayList<>();
}
private int parent(int i) {
return (i - 1) / 2;
}
private int left(int i) {
return 2 * i + 1;
}
private int right(int i) {
return 2 * i + 2;
}
private boolean hasParent(int i) {
return i > 0;
}
private boolean hasLeft(int i) {
return left(i) < heap.size();
}
private boolean hasRight(int i) {
return right(i) < heap.size();
}
private void swap(int i, int j) {
Node temp = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, temp);
}
public void offer(int key, String value) {
Node node = new Node(key, value);
heap.add(node);
int i = heap.size() - 1;
while (hasParent(i) && heap.get(i).key < heap.get(parent(i)).key) {
swap(i, parent(i));
i = parent(i);
}
}
public Node poll() {
if (heap.isEmpty()) {
throw new IllegalStateException("The priority queue is empty.");
}
Node minNode = heap.get(0);
heap.set(0, heap.remove(heap.size() - 1));
int i = 0;
while (hasLeft(i)) {
int minChildIndex = left(i);
if (hasRight(i) && heap.get(right(i)).key < heap.get(minChildIndex).key) {
minChildIndex = right(i);
}
if (heap.get(i).key < heap.get(minChildIndex).key) {
break;
}
swap(i, minChildIndex);
i = minChildIndex;
}
return minNode;
}
public boolean isEmpty() {
return heap.isEmpty();
}
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
pq.offer(3, "C");
pq.offer(1, "A");
pq.offer(2, "B");
while (!pq.isEmpty()) {
Node node = pq.poll();
System.out.println(node.key + " " + node.value);
}
}
}
This code snippet defines a Node class for storing key-value pairs and a PriorityQueue class that implements a Min-Heap based priority queue. The main methods are offer for adding a node to the priority queue and poll for removing and returning the node with the highest priority (in this case, the node with the lowest key value).
In the main method, a new PriorityQueue instance is created, and nodes with different priorities are added using the offer method. Finally, the poll method is used in a loop to remove and display nodes in the order of their priority.
Not yet included in a published release.