import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// 创建一个优先队列
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
// 添加元素到优先队列
priorityQueue.add(10);
priorityQueue.add(30);
priorityQueue.add(20);
priorityQueue.add(5);
// 打印优先队列的头部元素(最小值)
System.out.println("Head of the queue: " + priorityQueue.peek());
// 移除并返回队列中的头部元素
System.out.println("Removed element: " + priorityQueue.poll());
// 再次打印优先队列的头部元素
System.out.println("Head of the queue after poll: " + priorityQueue.peek());
// 遍历优先队列中的所有元素
System.out.println("Elements in the queue:");
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll());
}
}
}
Queue 接口的类,它是一个基于堆结构的优先队列。这个示例代码展示了如何创建一个优先队列、添加元素、获取和移除头部元素,并遍历队列中的所有元素。
上一篇:java return
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站