import java.util.Collections;
import java.util.PriorityQueue;
public class HeapTest {
public static void main(String[] args) {
// 创建一个小堆
PriorityQueue<Integer> minheap = new PriorityQueue<>();
// 创建一个大堆
PriorityQueue<Integer> maxheap = new PriorityQueue<>(Collections.reverseOrder());
// 添加元素
minheap.add(10);
minheap.add(8);
minheap.add(9);
minheap.add(11);
minheap.add(2);
minheap.add(10);
minheap.add(8);
minheap.add(9);
minheap.add(11);
minheap.add(2);
// [2, 8, 9, 11, 10]
System.out.println(minheap.toString());
// [11, 10, 9, 8, 2]
System.out.println(minheap.toString());
// 获取元素
minheap.peek();
maxheap.peek();
// 删除顶部元素
minheap.poll();
maxheap.poll();
// 堆大小
minheap.size();
maxheap.size();
// 迭代器
while (!minheap.isEmpty()){
System.out.println(minheap.poll());
}
}
}
11-08
2033
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-05
141
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交