用数组模拟STL中的srack(栈)和queue(队列)

时间:2023-03-09 21:31:58
用数组模拟STL中的srack(栈)和queue(队列)

我们在理解stack和queue的基础上可以用数组来代替这两个容器,因为STL中的stack和queue有可能会导致程序运行起来非常的慢,爆TLE,所以我们使用数组来模拟他们,不仅可以更快,还可以让代码更加简洁

1.数组模拟stack

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#define ll long long
const int N=1e6+10;
using namespace std;
typedef pair<int,int>PII;
int stk[N],tt=0; //插入
stk[++tt]=x; //弹出
tt--; //判断栈是否为空
if(tt>0) not empty;
else empty; //栈顶
stk[tt]; int main(){
ios::sync_with_stdio(false);
return 0;
}

2.数组模拟queue

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#define ll long long
const int N=1e6+10;
using namespace std;
typedef pair<int,int>PII; //在队尾插入元素,在队头弹出元素
int q[N],hh,tt=-1; //插入
q[++tt]=x; //弹出
hh++; //判度队列是否为空
if(hh<=tt) not emty;
else empty; //取出队头元素
q[hh]; int main(){
ios::sync_with_stdio(false);
return 0;
}

相关文章