C++ 实现队列操作:代码示例与解析
使用 C++ 实现队列操作:代码示例与解析
本文提供了一个使用 C++ 语言实现队列操作的代码示例,并详细解析了代码的逻辑和功能。示例代码包含 push、pop、empty 和 query 等常见队列操作,并使用输入输出流和字符串比较符进行操作控制。
#include <iostream>
using namespace std;
const int N = 100000;
int qu[N];
int head = 1;
int tail = 0;
void push(int x) {
qu[++tail] = x;
}
void pop() {
if (tail >= head)
head++;
else
cout << 'FBI WARNING' << endl;
}
bool empty() {
if (tail >= head)
return false;
else
return true;
}
int query() {
if (tail >= head)
return qu[head];
else {
cout << 'FBI WARNING' << endl;
return -1;
}
}
int main() {
int n;
cin >> n;
while (n--) {
string str;
cin >> str;
if (str == 'push') {
int x;
cin >> x;
push(x);
}
else if (str == 'pop') {
pop();
}
else if (str == 'empty') {
if (empty())
cout << 'YES' << endl;
else
cout << 'NO' << endl;
}
else if (str == 'query') {
cout << query() << endl;
}
}
return 0;
}
这段代码与之前的 C 语言代码实现了相同的队列操作,只是使用了 C++ 的输入输出流和字符串比较操作符。在主函数中,根据输入的操作命令执行相应的操作,并输出结果。
希望这段代码对你有帮助!如果还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/cskn 著作权归作者所有。请勿转载和采集!