My idea is to add data into an ArrayList, sort it and then return the data to the Stack. It sounds circuitous but do you guys have better implementation?
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();
}
}