为什么不能从PriorityQueue中删除peek()得到的元素?

问题描述 投票:0回答:1

这是我的代码。

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

在pop()函数中,PriorityQueue不会删除我从deque.peek()获得的最高值。当我将其更改为

pq.remove(deque.pollLast());   

有效。为什么会这样?

java deque peek
1个回答
2
投票

Deque.peek()返回双端队列的第一个元素,与peekFirst()相同。像在peekLast()中一样使用top()

© www.soinside.com 2019 - 2024. All rights reserved.