当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
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();
}
};
思路:
如有错误,多多指教
边栏推荐
- 数据分析知识点搜集(纯粹的搜集)
- Boss: There are too many systems in the company, can you realize account interoperability?
- 【开源框架】国内首个通用云计算框架,任意程序都可做成云计算。
- 直播预告 | 构建业务智联,快速拥抱财务数字化转型
- Walk the Maze BFS
- Golang Chapter 1: Getting Started
- 雅思大作文写作模版
- 【RYU】rest_router.py源码解析
- Recognized by International Authorities | Yunzhuang Technology was selected in "RPA Global Market Pattern Report, Q3 2022"
- .NET6之MiniAPI(十四):跨域CORS(上)
猜你喜欢

CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应

FinClip最易用的智能电视小程序

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

Summary bug 】 【 Elipse garbled solution project code in Chinese!

生成器版和查看器版有什么区别?

End-to-End Lane Marker Detection via Row-wise Classification

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

Pytest学习-setup/teardown
Causes of Mysql Disk Holes and Several Ways to Rebuild Tables

PowerMockup 4.3.4::::Crack
随机推荐
Unity2021发布WebGL雾效消失问题
rosbridge-WSL2 && carla-win11
一个函数有多少种调用方式?
Binary search tree to solve the fallen leaves problem
[2022强网杯] polydiv和gamemaster
Basic Concepts of Graphs
SPOJ 2774 Longest Common Substring(两串求公共子串 SAM)
start with connect by implements recursive query
V8中的快慢数组(附源码、图文更易理解)
End-to-End Lane Marker Detection via Row-wise Classification
With the rise of concepts such as metaverse and web3.0, many digital forms such as digital people and digital scenes have begun to appear.
2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis
LabVIEW code generation error 61056
PowerMockup 4.3.4::::Crack
Pytest学习-setup/teardown
Bytebase database schema change management tool
UVa 437 - The Tower of Babylon (White Book)
二叉搜索树解决落叶问题
Research status of target detection at home and abroad
Canvas App中点击图标生成PDF并保存到Dataverse中