前言
对列这部分也不难,只需要掌握队列的基本操作即可!!!
一、队列的基本概念
概念:
队列和我们之前学习的栈一样,它也是一种特殊的线性表。它只允许在一端插入数据,在另一端删除数据,不允许对中间的元素进行操作,因而也不支持随机访问。队列具有先进先出的特性。
基本操作:
入队: 队列 的插入操作叫做入队,插入数据的一端称作队头
出队: 队列 的删除操作叫做出队,删除数据的一端称作队尾
二、典型例题及AC代码
1.例题
2.代码
数组模拟:
//******************************队列
//在队尾插入元素,在队头弹出元素
//int q[N],hh,tt = -1;//hh表示对头,tt表示队尾
//1.插入
//q[++tt] = x;
//2.弹出
//hh++;
//3.判断队列是否为空
//if(hh<tt)not empty;
//else empty;
//4.取出队头元素
//q[hh]
#include <iostream>
using namespace std;
const int N = 100010;
int q[N], tt = 0, hh = 1;
//1.向队尾插入一个数x
void push(int x) {
q[++tt] = x;
}
//2.从队头弹出一个数
void pop() {
hh++;
}
//3.判断队列是否为空
void empty() {
if (hh <= tt)
cout << "NO" << endl;
else
cout << "YES" << endl;
}
//4.查询队头元素
void query() {
cout << q[hh] << endl;
}
int main() {
int m;
cin >> m;
string op;
while (m--) {
cin >> op;
if (op == "push") {
int x;
cin >> x;
push(x);
} else if (op == "pop") {
pop();
} else if (op == "empty") {
empty();
} else {
query();
}
}
return 0;
}
STL:
#include<iostream>
#include<queue>
using namespace std;
queue<int>q;
int x,m;
string s;
int main()
{
cin>>m;
while(m--){
cin>>s;
if(s=="push"){
cin>>x;
q.push(x);
}
if(s=="pop")
q.pop();
if(s=="empty"){
if(q.empty())cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
if(s=="query") cout<<q.front()<<endl;
}
return 0;
}