I am new to the concept of heaps and PQs. So I was trying to implement a Stack using PQ using a min heap. I am trying to implement following methods:
Below is the code:
import java.util.*;
import java.lang.System;
public class StackUsingMinPriorityQueue{
static int a[] = {3,7,2,11,9,4};
int size = 0;
PriorityQueue<Integer> pq;
static StackUsingMinPriorityQueue obj;
public static void main(String args[]){
obj = new StackUsingMinPriorityQueue(a.length);
for(int i=0;i<a.length;i++){
obj.push(a[i]);
}
System.out.println("Value popped: "+obj.pop());
System.out.println("Value at Top: "+obj.top());
System.out.println("PQ size: "+obj.size());
System.out.println("PQ IsEmpty: "+obj.isEmpty());
}
public StackUsingMinPriorityQueue(int size){
this.size = size;
pq = new PriorityQueue<Integer>();
}
/**
* 1. PUSH
* **/
public void push(int data){
obj.insert(-System.currentTimeMillis(),data);
}
public void insert(long time, int data) {
pq.offer(data);
}
/**
* 2. POP
*/
public int pop(){
return obj.extractMin();
}
public int extractMin() {
return pq.poll();
}
/**
* 3.TOP
*/
public int top(){
return pq.peek();
}
/**
* 4. SIZE
*/
public int size(){
return pq.size();
}
/**
* 5.IsEmpty
*/
public boolean isEmpty(){
return pq.isEmpty();
}
}
Output:
Value popped: 2
Value at Top: 3
PQ size: 5
PQ IsEmpty: false
Now, my query is the value at top =3 . Is this correct ? Shouldn't it be the last value entered i.e 4? My understanding is that as we are implementing a stack, a peek shall give the element at the top of the stack which shall be 4 and not 3.
Can someone please let me know if my implementation is incorrect or is my understanding?
pq.poll()
and pq.peek()
operates on the minimal element in the pq
, while pop
and top
should return last inserted element.
To implement a stack using priority queue, you should add a key -<insertion time>
to each value. You may use plain increasing counter as a "timer". Notice, that this implementations will be very inefficient.