目录
1.优先级队列
1.1 概念
1.2 内部原理
1.3 操作-入队列
过程(以大堆为例):
图示:
3.4 操作-出队列(优先级最高)
3.5 借用堆实现优先级队列
1.实现一个接口
public interface IQueue<E> {
// 入队
void offer(E val);
//出队
E poll();
//返回队首元素
E peek();
//判断队列是否为空
boolean isEmpty();
}
2.堆完整代码见上节
3.优先级队列
/**
* 基于最大堆的优先级队列,值越大优先级越高
* 队首元素就是优先级最大的元素(值最大)
*/
import stack_queue.queue.IQueue;
public class PriorityQueue implements IQueue<Integer> {
MaxHeap heap = new MaxHeap();
public PriorityQueue(){
heap = new MaxHeap();
}
@Override
public void offer(Integer val) {
heap.add(val);
}
@Override
public Integer poll() {
return heap.extractMax();
}
@Override
public Integer peek() {
return heap.peekMax();
}
@Override
public boolean isEmpty() {
return heap.isEmpty();
}
}
3.6 测试
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueTest {
public static void main(String[] args) {
// 通过构造方法传入比较器
// 默认是最小堆,"值"(比较器compare的返回值)越小,优先级就越高
// 当传入一个降序的比较器时,值(比较器compare的返回值,值越大,返回负数)
// Queue<Student> queue = new PriorityQueue<>(new StudentComDesc());
// Queue<Student> queue = new PriorityQueue<>(new Comparator<Student>() {
// @Override
// public int compare(Student o1, Student o2) {
// return o2.getAge() - o1.getAge();
// }
// });
Queue<Student> queue = new PriorityQueue<>(new StudentCom());
Student stu1 = new Student(40,"铭哥");
Student stu2 = new Student(20,"龙哥");
Student stu3 = new Student(18,"蛋哥");
queue.offer(stu1);
queue.offer(stu2);
queue.offer(stu3);
while (!queue.isEmpty()){
System.out.println(queue.poll());
}
}
}
//升序(最小堆)
class StudentCom implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
}
//降序(最大堆)
class StudentComDesc implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge() - o1.getAge();
}
}
class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}