当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
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();
}
};
思路:
如有错误,多多指教
边栏推荐
- With 4 years of work experience, the 5 communication methods between multi-threads can't be said, can you believe it?
- Embedded systems: overview
- [2022安恒夏令营] 5个小题
- BMN: Boundary-Matching Network for Temporal Action Proposal Generation阅读笔记
- Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
- Create function report error, prompting DECLARE definition syntax problem
- Storage engine written by golang, based on b+ tree, mmap
- What is Adobe?
- 使用tf.image.resize() 和tf.image.resize_with_pad()调整图像大小
- Golang第二章:程序结构
猜你喜欢
Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
目标检测技术研究现状及发展趋势
直播预告 | 构建业务智联,快速拥抱财务数字化转型
牛客2022 暑期多校3 H Hacker(SAM + 线段树查询区间内部最大子段和)
SPOJ 2774 Longest Common Substring(两串求公共子串 SAM)
HCIP BGP实验报告
Live Preview | Build Business Intelligence, Quickly Embrace Financial Digital Transformation
Zilliz 2023 秋季校园招聘正式启动!
设置工作模式与环境(下):探查和收集信息
2022-08-03 oracle执行慢SQL-Q17对比
随机推荐
[2022强网杯] polydiv和gamemaster
utils timer
Scala基础【正则表达式、框架式开发原则】
ML之yellowbrick:基于titanic泰坦尼克是否获救二分类预测数据集利用yellowbrick对LoR逻辑回归模型实现可解释性(阈值图)案例
云平台建设解决方案
Recognized by International Authorities | Yunzhuang Technology was selected in "RPA Global Market Pattern Report, Q3 2022"
如何创建一个Web项目
Zilliz 2023 Fall Campus Recruitment Officially Launched!
Golang第二章:程序结构
二叉搜索树解决落叶问题
Storage engine written by golang, based on b+ tree, mmap
【论文阅读】TRO 2021: Fail-Safe Motion Planning for Online Verification of Autonomous Vehicles Using Conve
HDU 5655 CA Loves Stick
Software testing is seriously involution, how to improve your competitiveness?
软测人每个阶段的薪资待遇,快来康康你能拿多少?
The sword refers to the offer question 22 - the Kth node from the bottom in the linked list
V8中的快慢数组(附源码、图文更易理解)
Cisco ike2 IPSec configuration
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
工作小计 QT打包