MinHeap MaxHeap using Queue (PriorityQueue)

package com.test;
 
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
 
public class PriorityQueueExample {
 
    public static void main(String[] args) {
        <span style="color:#3366ff;">Queue<Integer> qi = new PriorityQueue<Integer>();</span>
 
        qi.add(5);
        qi.add(2);
        qi.add(1);
        qi.add(10);
        qi.add(3);
 
        <span style="color:#3366ff;">while (!qi.isEmpty()) {
            System.out.print(qi.poll() + ",");
        }</span>
        System.out.println();
        System.out.println("-----------------------------");
        // <span></span><span>自定义的比较器,可以让我们自由定义比较的顺序</span> Comparator<Integer> cmp;
        <span style="color:#3366ff;">cmp = new Comparator<Integer>() { 
            public int compare(Integer e1, Integer e2) {
                return e2 - e1;
            }
        };</span>
        Queue<Integer> q2 = new PriorityQueue<Integer>(5, cmp);
        q2.add(2);
        q2.add(8);
        q2.add(9);
        q2.add(1);
        while (!q2.isEmpty()) {
            System.out.print(q2.poll() + ",");
        }
 
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值