Files
python/TangDou/LuoGuBook/15_3_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

65 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
//队列的模板
const int N = 100010;
int q[N], del[N], hh = 0, tt = -1;
void push(int x) {
q[++tt] = x;
}
//将标识为删除状态的数据弹出
void popEmpty() {
while (del[hh]) hh++;
}
//判断队列是否为空
bool empty() {
if (hh <= tt) return false;
else {
//清空头部
popEmpty();
//遍历每个元素,是不是存在未删除的元素
for (int i = hh; i <= tt; i++)
if (del[hh] == 0) return false;
return true;
}
}
void Pop() {
popEmpty();
hh++;//弹出第一个非零的数据
}
int Top() {
popEmpty();
return q[hh];
}
void Delete(int x) {
//因为是单调递增的,所以可以使用二分策略找到最小值
int pos = lower_bound(q + hh, q + tt + 1, x) - q;
if (q[pos] != x) return; //可能找不到,返回的是第一个大于等于x的数字
//打上标识
del[pos] = 1;
}
const int n = 7;
int a[n] = {1, 3, 3, 5, 6, 8, 9};
int main() {
//初始化队列
for (int i = 0; i < n; i++) push(a[i]);
//测试Top
cout << Top() << endl;
//测试Pop
Pop();
//测试Delete
Delete(3);
//输出队列内容
for (int i = hh; i <= tt; i++)
if (!del[i]) cout << q[i] << " ";
return 0;
}