我的想法是将数据添加到ArrayList中,对其进行排序,然后将数据返回到堆栈。这听起来很迂回,但你们有更好的实施吗?使用堆栈实现优先级队列
class MyPriorityQueue {
private Stack<Integer> st;
private ArrayList<Integer> list;
public MyPriorityQueue() { // The constructor
st = new Stack<Integer>();
list = new ArrayList<Integer>();
}
public void add(int e) { // To add one more item
list.add(e);
}
public int poll() { // To remove one item
if(!list.isEmpty())
sortListAndTransferToStack();
System.out.println("st.peek(): " + st.peek());
return st.pop();
}
private void sortListAndTransferToStack() {
Collections.sort(list, Collections.reverseOrder());
st.clear();
for(int i=0; i<list.size(); i++) {
st.push(list.get(i));
}
list.clear();
}
public boolean isEmpty() { // To check whether the priority queue is empty. Don't modify this method
return st.isEmpty();
}
}
是什么问题? isEmpty方法 – Kick
为什么不使用[现有优先级队列](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html)[实施](http:// docs .oracle.com/JavaSE的/ 7 /文档/ API/JAVA/util的/并行/ PriorityBlockingQueue.html)? – zapl
这是一项家庭作业。 isEmpty()在骨架中。该任务要求使用堆栈实现优先队列。 – uohzxela