簡體   English   中英

為什么我不能從 PriorityQueue 中刪除 peek() 獲取的元素?

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

這是我的代碼。

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();
    }
}

在 function pop() 中,PriorityQueue 不會刪除我從 deque.peek() 獲得的最高值。 當我將其更改為

pq.remove(deque.pollLast());   

有效。 這是為什么?

Deque.peek()返回雙端隊列的第一個元素,與peekFirst()相同。 像在top()中那樣使用peekLast() ) 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM