Implement stack and queue APIs using heaps
StackQueueUsingHeapTemplate.javaprivate static class Compare<T> implements Comparator<Pair<Integer, T>> {
@Override
public int compare(Pair<Integer, T> o1, Pair<Integer, T> o2) {
return o2.getFirst().compareTo(o1.getFirst());
}
}
public static class Stack<T> {
private int order = 0;
private PriorityQueue<Pair<Integer, T>> H = new PriorityQueue<>(
11, new Compare<T>());
public void push(T x) {
H.add(new Pair<Integer, T>(order++, x));
}
public T pop() {
return H.remove().getSecond();
}
public T peek() {
return H.peek().getSecond();
}
}
public static class Queue<T> {
private int order = 0;
private PriorityQueue<Pair<Integer, T>> H = new PriorityQueue<>(
11, new Compare<T>());
public void enqueue(T x) {
H.add(new Pair<Integer, T>(order--, x));
}
public T dequeue() {
return H.remove().getSecond();
}
public T head() {
return H.peek().getSecond();
}
}