Search code examples
javapriority-queue

Removing tail element of priority queue


How can I remove the tail element of a priority queue? I am trying to implement beam search using a priority queue and once the priority queue is full, I want to remove the last element(the element with the least priority).

Thanks!


Solution

  • No easy way. Copy elements from original to new except the last.

    PriorityQueue removelast(PriorityQueue pq)
    {
    
        PriorityQueue pqnew = new PriorityQueue();
    
        while(pq.size() > 1)
        {
            pqnew.add(pq.poll());
        }
    
        pq.clear();
        return pqnew;
    }
    

    called as

    pq = removelast(pq);