Java堆结构PriorityQueue

在Java1.5中引入了PriorityQueue(优先队列),PriorityQueue默认实现了最小堆,也可以传入Comparetor来实现最大堆。
实验代码如下:

import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //优先队列的使用 默认实现的是最小堆
        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
        pQueue.add(12);
        pQueue.add(56);
        pQueue.add(2);
        pQueue.add(34);
        pQueue.add(89);
        System.out.println("*****打印最小堆****");
        for (Integer integer : pQueue) {
            System.out.print(integer+" ");
        }
        System.out.println();
        System.out.println("*****最小堆依次出队列(升序)****");
        while(!pQueue.isEmpty()){
            System.out.print(pQueue.poll()+" ");
        }
        System.out.println();
        /**最大堆**/
        int initialCapacity = 100;
        PriorityQueue<Integer> pQueue1 = new PriorityQueue<Integer>(
                initialCapacity,
                new Comparator<Integer>(){

                    @Override
                    public int compare(Integer o1, Integer o2) {
                        // TODO Auto-generated method stub
                        //return 02 - o1;
                        if(o1>o2)
                            return -1;
                        if(o1<o2)
                            return 1;
                        return 0;
                    }

                });
        pQueue1.add(12);
        pQueue1.add(56);
        pQueue1.add(2);
        pQueue1.add(34);
        pQueue1.add(89);
        System.out.println("*****打印最大堆****");
        for (Integer integer : pQueue1) {
            System.out.print(integer+" ");
        }
        System.out.println();
        System.out.println("*****最大堆依次出队列(降序)****");
        while(!pQueue1.isEmpty()){
            System.out.print(pQueue1.poll()+" ");
        }
    }

}

实验结果:

*****打印最小堆****
2 34 12 56 89 
*****最小堆依次出队列****
2 12 34 56 89 
*****打印最大堆****
89 56 2 12 34 
*****最大堆依次出队列****
89 56 34 12 2 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值