Java 中的最大堆
最大堆是一个完全二叉树,其中每一步的根节点的值大于或等于子节点的值。
下面是一个使用库函数实现的最大堆。
示例
import java.util.*;
public class Demo{
public static void main(String args[]){
PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());
my_p_queue.add(43);
my_p_queue.add(56);
my_p_queue.add(99);
System.out.println("The elements in the priority queue are : ");
Iterator my_iter = my_p_queue.iterator();
while (my_iter.hasNext())
System.out.println(my_iter.next());
my_p_queue.poll();
System.out.println("After removing an element using the poll function, the queue elements are :");
Iterator<Integer> my_iter_2 = my_p_queue.iterator();
while (my_iter_2.hasNext())
System.out.println(my_iter_2.next());
Object[] my_arr = my_p_queue.toArray();
System.out.println("The array representation of max heap : ");
for (int i = 0; i < my_arr.length; i++)
System.out.println("Value: " + my_arr[i].toString());
}
}输出
The elements in the priority queue are : 99 43 56 After removing an element using the poll function, the queue elements are : 56 43 The array representation of max heap : Value: 56 Value: 43
名为 Demo 的类包含 main 函数。在 main 函数内,定义优先级的队列实例并使用“add”函数向其中添加元素。定义一个迭代器,并
用于遍历优先级队列中的元素。“poll”函数用于从列表中删除一个元素。接下来,迭代元素并显示在屏幕上。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP