Creat a PriorityQueue class that uses a binary minheap for i
Creat a PriorityQueue class that uses a binary min-heap for its implementation. The constructor will takes one argument, the initial size of a queue.
1) public void add(T e) - Inserts the specified element \'e\' into this priority queue. Throws NullPointerException if the specified element is null.
2) public T poll() Retrieves the head of the this priority queue (smallest element), or null if the queue is empty.
Solution
//PriorityQueue implemention with binary min heap program in java
package com.chegg;
import java.util.PriorityQueue;
public class PriorityQueue1 {
PriorityQueue<Integer> pq ;
//Constructor which takes an argument size
public PriorityQueue1(int size) {
pq = new PriorityQueue<Integer>(size);
}
//inserts the element returns and throws null pointer exception if the element is null
public void add(int[] x) {
try{
for (int i = 0; i < x.length; i++) {
pq.offer(x[i]);
}}
catch(NullPointerException ne){
ne.printStackTrace();
}
}
//Retrieves the head of this queue.
public Integer poll(){
return pq.poll();
}
//Prints the elements of Priority Queue
public void print() {
System.out.println(pq);
}
public static void main(String[] args) {
int[] x = { 1, 6, 2, 9, 4, 3, 8 };
PriorityQueue1 pq = new PriorityQueue1(10);
pq.add(x);
pq.print();
System.out.println(\"The head of the Queue is: \"+pq.poll());
pq.print();
}
}
Output:
[1, 4, 2, 9, 6, 3, 8]
The head of the Queue is: 1
[2, 4, 3, 9, 6, 8]

