当前位置:网站首页>用队列模拟实现栈
用队列模拟实现栈
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();
}
};
思路:
如有错误,多多指教
边栏推荐
- 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!
- Click the icon in Canvas App to generate PDF and save it to Dataverse
- Bytebase database schema change management tool
- 设置工作模式与环境(下):探查和收集信息
- 软测人每个阶段的薪资待遇,快来康康你能拿多少?
- .NET6之MiniAPI(十四):跨域CORS(上)
- MCS-51单片机,定时1分钟,汇编程序
- [MySQL Advanced] Creation and Management of Databases and Tables
- How to write a database document management tool based on WPF (2)
- Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
猜你喜欢

3D 语义分割——2DPASS

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!

Embedded Systems: Clocks

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

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

redis持久化方式

AOSP CameraLatencyHistogram的原理与使用

What is Adobe?

【开源框架】国内首个通用云计算框架,任意程序都可做成云计算。

Scala基础【正则表达式、框架式开发原则】
随机推荐
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!
LabVIEW code generation error 61056
Pytest学习-setup/teardown
BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes
OPC UA 与IEC61499 深度融合(1)
Cloud platform construction solutions
Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
《数字经济全景白皮书》金融数字用户篇 重磅发布!
Quickly build a website with static files
[2022强网杯] polydiv和gamemaster
UVa 437 - The Tower of Babylon(白书)
The principle and use of AOSP CameraLatencyHistogram
start with connect by implements recursive query
[MySQL Advanced] Creation and Management of Databases and Tables
什么是memoization,它有什么用?
Embedded systems: overview
FinClip,助长智能电视更多想象空间
Unity2021发布WebGL雾效消失问题
目标检测技术研究现状及发展趋势
Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo