public class PriorityQueueDemo {
public static void main(String[] args) {
// 创建小顶堆(默认)
System.out.println("=== 小顶堆示例 ===");
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// 添加元素
minHeap.offer(5);
minHeap.offer(1);
minHeap.offer(10);
minHeap.offer(3);
System.out.println("小顶堆出队顺序:");
while (!minHeap.isEmpty()) {
System.out.print(minHeap.poll() + " "); // 输出:1 3 5 10
}
System.out.println("\n\n=== 大顶堆示例 ===");
// 使用Comparator创建大顶堆
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
maxHeap.offer(5);
maxHeap.offer(1);
maxHeap.offer(10);
maxHeap.offer(3);
System.out.println("大顶堆出队顺序:");
while (!maxHeap.isEmpty()) {
System.out.print(maxHeap.poll() + " "); // 输出:10 5 3 1
}
System.out.println("\n\n=== 字符串优先队列 ===");
PriorityQueue<String> stringQueue = new PriorityQueue<>();
stringQueue.offer("banana");
stringQueue.offer("apple");
stringQueue.offer("cherry");
System.out.println("字符串小顶堆出队顺序:");
while (!stringQueue.isEmpty()) {
System.out.print(stringQueue.poll() + " "); // 按字典序输出
}
}
}