文章目录
一、队列基础知识
队列是典型的先进先出的线性数据结构。有两个特点
- 队列中数据是按照先进先出方式进出队列的。
- 队列只允许在队首进行删除操作,而在队尾进行插入操作。
可以用数组来实现队列,称为队列的顺序存储;还可以用链表来实现队列,称为队列的链式存储。
队列分为:普通队列,循环队列,优先队列
二、队列基本操作
c++队列常用六种函数:C++队列中的常用函数
- 入队,如例:q.push(x); 将x 接到队列的末端。
- 出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
- 显示第一个元素,如例:q.front(),即最早被压入队列的元素。
- 显示最后一个元素,如例:q.back(),即最后被压入队列的元素。
- 判断队列空,如例:q.empty(),当队列空时,返回true。
- 定义一个queue,如例:queue<type> myqueue;
- 显示队列长度,如例:q.size()
三、c++ STL库实现队列的代码
#include <iostream>
#include <iostream>
#include <queue>//需要头文件
using namespace std;
int main() {
// 1. Initialize a queue.
queue<int> q;
// 2. Push new element.
q.push(5);
q.push(13);
q.push(8);
q.push(6);
// 3. Check if queue is empty.
if (q.empty()) {
cout << "Queue is empty!" << endl;
return 0;
}
// 4. Pop an element.
q.pop();
// 5. Get the first element.
cout << "The first element is: " << q.front() << endl;
// 6. Get the last element.
cout << "The last element is: " << q.back() << endl;
// 7. Get the size of the queue.
cout << "The size is: " << q.size() << endl;
}
四、用数组实现循环队列的代码
数组循环队列的实现只需要灵活的改变front和rear指针即可。
用数组实现循环队列,判断队列满的两种标志
- (rear+1)%MAXSIZE=front (尾指针追上头指针)
- arr.size=MAXSIZE (数组的大小等于MAXSIZE)
用数组实现循环队列,判断队列空的一种标志
- arr.size=0 (数组的大小等于MAXSIZE)
#define MAX_SIZE 5
struct Queue {
int count;//计数
int front;
int rear;
int data[MAX_SIZE];
};
class xunhuan_duilie
{
public:
/*初始化循环队列*/
void Init(Queue* ptr)
{
ptr->count = 0;
ptr->front = 0;
ptr-