简体   繁体   English

为什么我不能从 PriorityQueue 中删除 peek() 获取的元素?

[英]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().在 function pop() 中,PriorityQueue 不会删除我从 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() . Deque.peek()返回双端队列的第一个元素,与peekFirst()相同。 Use peekLast() instead like you did in top() .像在top()中那样使用peekLast() ) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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