当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
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();
}
};
思路:
如有错误,多多指教
边栏推荐
- 2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis
- On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
- What is memoization and what is it good for?
- Bytebase database schema change management tool
- 云平台建设解决方案
- 3D 语义分割——2DPASS
- Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
- 软件测试内卷严重,如何提升自己的竞争力呢?
- Kotlin - 扩展函数和运算符重载
- 目标检测的国内外研究现状
猜你喜欢

Embedded Systems: GPIO

ML之interpret:基于titanic泰坦尼克是否获救二分类预测数据集利用interpret实现EBC模型可解释性之全局解释/局部解释案例

Zilliz 2023 秋季校园招聘正式启动!

PowerMockup 4.3.4::::Crack

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

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

Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting

On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use

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

Embedded systems: overview
随机推荐
直播预告 | 构建业务智联,快速拥抱财务数字化转型
Embedded systems: overview
【MySQL进阶】数据库与表的创建和管理
云计算国内外发展现状
Scala基础【正则表达式、框架式开发原则】
完全二叉树问题
Cloud platform construction solutions
Websocket multi-threaded sending message error TEXT_PARTIAL_WRITING--Use case of spin lock replacing synchronized exclusive lock
With 4 years of work experience, the 5 communication methods between multi-threads can't be said, can you believe it?
【RYU】rest_router.py源码解析
On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析
OPC UA 与IEC61499 深度融合(1)
node连接mysql数据库报错:Client does not support authentication protocol requested by server
rosbridge-WSL2 && carla-win11
牛客2022 暑期多校3 H Hacker(SAM + 线段树查询区间内部最大子段和)
Research status of target detection at home and abroad
Nine ways to teach you to read the file path in the resources directory
创建函数报错,提示DECLARE定义语法问题