简体   繁体   中英

Why can't I remove an element gotten by peek() from the PriorityQueue?

Here is my code.

class MinStack {
    public Deque<Integer> deque = new LinkedList<Integer>();
    public PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

    public MinStack() {
        Deque<Integer> deque = new LinkedList<Integer>();
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    }

    public void push(int x) {
        deque.offer(x);
        pq.offer(x);
    }

    public void pop() {
        pq.remove(deque.peek()); 
        deque.pollLast();        
    }

    public int top() {
        return deque.peekLast();
    }

    public int getMin() {
        return pq.peek();
    }
}

In the function pop(), the PriorityQueue doesn't delete the top value I get from the deque.peek(). When I changed it to

pq.remove(deque.pollLast());   

It worked. Why is that?

Deque.peek() returns the first element of the deque, same as peekFirst() . Use peekLast() instead like you did in top() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM