I'm using the Deque
to implement a monotonic queue. I know that Deque
can be created by both ArrayDeque
and LinkedList
. Here is the Monotonic class I constructed:
public static class MonotonicQueue {
Deque<Integer> monotonicQueue;
public MonotonicQueue() {
monotonicQueue = new ArrayDeque<>();
}
void push(int n) {
while (!monotonicQueue.isEmpty() && monotonicQueue.getLast() < n) {
monotonicQueue.removeLast();
}
monotonicQueue.addLast(n);
}
int max() {
return monotonicQueue.getFirst();
}
void pop(int n) {
if (!monotonicQueue.isEmpty() && n == monotonicQueue.getFirst()) {
monotonicQueue.removeFirst();
}
monotonicQueue.addLast(n);
}
}
However, the issue appears in the void push(int n)
method, which means delete all elements which are < n
, and then add n
into the queue of the tail. I initialized a variable window
in a method and then tried to push an element to update this monotonic queue.
MonotonicQueue window = new MonotonicQueue();
window.push(3);
But it even fails to insert the first element. The weird thing is when I use the second way in the constructor, say LinkedList<>
instead of ArrayDeque
, it works very well, i.e. 3 can be inserted successfully.
public MonotonicQueue() {
monotonicQueue = new LinkedList<>();
}
I am wondering why one way works but the other can't. What happened here? Thank you!