当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
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();
}
};
思路:
如有错误,多多指教
边栏推荐
- 重发布实验报告
- IELTS essay writing template
- [N1CTF 2018] eating_cms
- Zilliz 2023 秋季校园招聘正式启动!
- 云平台建设解决方案
- Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
- 2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis
- utils timer
- Embedded systems: overview
- node连接mysql数据库报错:Client does not support authentication protocol requested by server
猜你喜欢

"Digital Economy Panorama White Paper" Financial Digital User Chapter released!

pikachu Over permission

静态文件快速建站

Embedded Systems: GPIO

软测人每个阶段的薪资待遇,快来康康你能拿多少?

Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!

《数字经济全景白皮书》金融数字用户篇 重磅发布!

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

Deep integration of OPC UA and IEC61499 (1)

Embedded Systems: Clocks
随机推荐
FinClip最易用的智能电视小程序
静态文件快速建站
一个函数有多少种调用方式?
Summary bug 】 【 Elipse garbled solution project code in Chinese!
Makefile
为什么我们需要回调
SPOJ 2774 Longest Common Substring(两串求公共子串 SAM)
设置工作模式与环境(下):探查和收集信息
ML之interpret:基于titanic泰坦尼克是否获救二分类预测数据集利用interpret实现EBC模型可解释性之全局解释/局部解释案例
云平台建设解决方案
Embedded Systems: GPIO
Interpretation of ML: A case of global interpretation/local interpretation of EBC model interpretability based on titanic titanic rescued binary prediction data set using interpret
软测人每个阶段的薪资待遇,快来康康你能拿多少?
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
log4j-slf4j-impl cannot be present with log4j-to-slf4j
FinClip,助长智能电视更多想象空间
代码随想录笔记_动态规划_416分割等和子集
Adobe是什么?
utils 定时器
Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting