我对堆和 PQ 的概念不熟悉。所以我试图使用最小堆使用 PQ 来实现堆栈。我正在尝试实现以下方法:
- 流行音乐
- 流行音乐
- 是空的
- 最佳
- 尺寸
下面是代码:
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
现在,我的查询是top =3 的值。它是否正确 ?它不应该是输入的最后一个值,即 4 吗?我的理解是,当我们正在实现一个堆栈时,一瞥应该会给出堆栈顶部的元素,该元素应为 4 而不是 3。
如果我的实施不正确或我的理解,有人可以告诉我吗?