hello i wonder what's wrong with my code: It should have an output like this:
in this problem I need to implement different queue operations by adding element, removing element, size of priority queue, print the queue and top element of queue
Input Format
The first line of input contains an integer T denoting the no of test cases. For each test case, the first line of input contains an integer Q denoting the no of queries followed by Q space separated queries. A query can be of the following types:
1.x (Adding x to the priority queue and print the queue)
2.(Removing the element from the top of the priority queue and printing that element )
3.(Get the element at the top of the priority queue)
4.(Get the size of the priority queue)
5.(Print the priority queue)
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
class Solution {
public static void main(String args[]) {
Scanner scanner= new Scanner(System.in);
int T=scanner.nextInt();
int i=0;
int Q=scanner.nextInt();
System.out.println();
PriorityQueue<Integer>pq=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
while (i<T){
for (int j = 0; j < Q; j++) {
int query=scanner.nextInt();
switch (query){
case 1:
pq.add(scanner.nextInt());
System.out.println(pq.toString().replace("[","").replace("]","").replace(",",""));
break;
case 2:
System.out.println(pq.poll());
break;
case 3:
System.out.println(pq.peek());
break;
case 4:
System.out.println(pq.size());
break;
case 5:
System.out.println(pq.toString().replace("[","").replace("]","").replace(",",""));
default:
break;
}}
i++;
}}
}
but when I'm running my code it gives me output like this:
Your queue printing code have some problems, try this code instead:
public static void printQueue(PriorityQueue<Integer> p1)
{
PriorityQueue<Integer> p2 = new PriorityQueue<>(p1);
while (!p2.isEmpty())
{
System.out.print(p2.poll() + " ");
}
System.out.println();
}
You can find the explanation here: