优先队列,PriorityQueue。
首先我们明白队列是一种先进先出的数据结构,其在队列尾追加,在队列头删除,然后在队列尾部添加;
在优先队列中,当访问元素的时候,具有高优先级元素最先被删除,优先队列具有高级先楚的行为特征。通常用堆数据结构来实现。

过程

入队操作:

  1. 插入节点5

image.png

  1. 新节点5上浮到合适位置。

image.png

出队操作

  1. 原堆节点10出队

image.png

  1. 最后一个节点1替换到堆顶位置

image.png

  1. 最后一个节点1替换到堆顶位置

image.png

Java中优先队列的使用

Java中优先队列是 Java.util包下的一个类PriorityQueue,其继承了CollectionQueue接口。

  1. //构造方法
  2. PriorityQueue(); //创建一个优先队列,默认初始容量为11.根据自然排序进行排序
  3. PriorityQueue(Comparator<? super E> comparator); //创建并根据指定的比较器对其元素进行排序
  4. //常用方法
  5. boolean add(E e); //插入
  6. boolean contains(Object o); //是否含有某个元素
  7. boolean offer(E e); //插入元素
  8. E peek(E e); //检索但是不删除此队列的头,如果为空,返回null
  9. E poll(E e); //检索并且删除此队列的头,如果为空,返回null
  10. int size(); //返回大小

Demo Test:

C++中优先队列的使用

此类包含在 头文件 <queue>中.
定义 :

  1. priority_queue<Type, Container, Functional>
  2. //1. Type : 数据类型
  3. //2. Container: 容器类型,必须是用数组实现的容器。默认是vector
  4. //3. Functional:比较的方式,默认是大顶堆
  5. Example
  6. //升序队列:小顶堆,比较小的元素先弹出
  7. priority_queue <int,vector<int>,greater<int> > q;
  8. //降序队列:大顶堆,比较大的元素先弹出6
  9. priority_queue <int,vector<int>,less<int> >q;

方法:

  1. top(); //访问对头元素
  2. empty(); //队列是否为空
  3. size(); //返回队列大小
  4. push(); //插入元素并且排序
  5. emplace(); //原地构造一个元素并且插入排队列
  6. pop(); //弹队头元素
  7. swqp(); //交换内容

Demo:

  1. #include<iostream>
  2. #include <queue>
  3. using namespace std;
  4. int main()
  5. {
  6. //对于基础类型 默认是大顶堆
  7. priority_queue<int> a;
  8. //等同于 priority_queue<int, vector<int>, less<int> > a;
  9. priority_queue<int, vector<int>, greater<int> > c; //这样就是小顶堆
  10. priority_queue<string> b;
  11. for (int i = 0; i < 5; i++)
  12. {
  13. a.push(i);
  14. c.push(i);
  15. }
  16. while (!a.empty())
  17. {
  18. cout << a.top() << ' ';
  19. a.pop();
  20. }
  21. cout << endl;
  22. while (!c.empty())
  23. {
  24. cout << c.top() << ' ';
  25. c.pop();
  26. }
  27. cout << endl;
  28. b.push("abc");
  29. b.push("abcd");
  30. b.push("cbd");
  31. while (!b.empty())
  32. {
  33. cout << b.top() << ' ';
  34. b.pop();
  35. }
  36. cout << endl;
  37. return 0;
  38. }
  39. //Output
  40. 4 3 2 1 0
  41. 0 1 2 3 4
  42. cbd abcd abc