当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
2022-08-03 22:55:00 【老鱼37】

思路:
class MyStack {
//创建两个队列
queue<int>q1;
queue<int>q2;
public:
MyStack() {
}
void push(int x) {
q2.push(x);//插入临时队列
while(!q1.empty())//判断q1是否为空
{
//不为空
q2.push(q1.front());
q1.pop();
}
swap(q1,q2);//交换
}
int pop() {
int x=q1.front();
q1.pop();
return x;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();//只需要判断q1就行了,q2是临时队列,一直为空
//q2是用来过渡的
}
};
解法二:
只用一个队列,在原队列上面改变:
class MyStack {
public:
queue<int>q;
MyStack() {
}
void push(int x) {
int num=q.size();
q.push(x);
for(int i=0;i<num;i++)
{
q.push(q.front());
q.pop();
}
}
int pop() {
int x=q.front();
q.pop();
return x;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};
思路:
如有错误,多多指教
边栏推荐
- BMN: Boundary-Matching Network for Temporal Action Proposal Generation阅读笔记
- utils timer
- IELTS essay writing template
- Adobe是什么?
- Nine ways to teach you to read the file path in the resources directory
- Click the icon in Canvas App to generate PDF and save it to Dataverse
- UVa 437 - The Tower of Babylon(白书)
- 目标检测技术研究现状及发展趋势
- Work Subtotal QT Packing
- 什么是memoization,它有什么用?
猜你喜欢

redis持久化方式

数据分析知识点搜集(纯粹的搜集)

获国际权威认可 | 云扩科技入选《RPA全球市场格局报告,Q3 2022》

Gains double award | know micro easily won the "2021 China digital twin solution suppliers in excellence" "made in China's smart excellent recommended products" double award!

The principle and use of AOSP CameraLatencyHistogram

Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting

冰河又一MySQL力作出版(文末送书)!!

【MySQL进阶】数据库与表的创建和管理

BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes

【论文阅读】TRO 2021: Fail-Safe Motion Planning for Online Verification of Autonomous Vehicles Using Conve
随机推荐
noip preliminary round
藏宝计划TreasureProject(TPC)系统模式开发技术原理
Kotlin - 扩展函数和运算符重载
Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting
举一个 web worker 的例子
How to write a database document management tool based on WPF (2)
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
Redis persistence method
2022-08-03 oracle执行慢SQL-Q17对比
亿流量大考(2):开发一套高容错分布式系统
伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
win10系统下yolov5-V6.1版本的tensorrt部署细节教程及bug修改
utlis 线程池
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
Embedded Systems: GPIO
软测人每个阶段的薪资待遇,快来康康你能拿多少?
LabVIEW代码生成错误 61056
【day6】类与对象、封装、构造方法
3D 语义分割——2DPASS