Java中PriorityQueue优先队列

PriorityQueue使用跟普通队列一样,唯一区别是PriorityQueue会根据排序规则决定谁在队头,谁在队尾。

PriorityQueue 通过add方法添加,通过poll方法一次获得一个最小元素,实现原理小顶堆,也就是说元素按照小顶堆结构存放。

public static void main(String[] args) {
    PriorityQueue<Integer> q = new PriorityQueue<>();
    //入列
    q.offer(1);
    q.offer(2);
    q.offer(5);
    q.offer(3);
    q.offer(4);
    //出列
    System.out.println(q.poll());  //1
    System.out.println(q.poll());  //2
    System.out.println(q.poll());  //3
    System.out.println(q.poll());  //4
    System.out.println(q.poll());  //5
}

同样也可以实现大根堆

public static void main(String[] args) {
    // Lambda表达式 实际就是强行上实现Comparable接口的对象的集合的自然顺序相反
    PriorityQueue<Integer> q = new PriorityQueue<>((x, y) -> (y - x));
    //入列
    q.offer(1);
    q.offer(2);
    q.offer(5);
    q.offer(3);
    q.offer(4);
    //出列
    System.out.println(q.poll());  //5
    System.out.println(q.poll());  //4
    System.out.println(q.poll());  //3
    System.out.println(q.poll());  //2
    System.out.println(q.poll());  //1
}

猜你喜欢

转载自blog.csdn.net/a792396951/article/details/113975549