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”函式用於從列表中刪除一個元素。接下來,迭代元素並顯示在螢幕上。
廣告