C++版 - 剑指offer 面试题7:用两个栈实现队列 题解
2024-10-09 13:18:58
用两个栈实现队列
参与人数:6484 时间限制:1秒 空间限制:32768K
用两个栈实现一个队列的功能?请给出算法和思路!
<分析>:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中的每个元素pop,并push进栈B,取出栈B的顶端值并将其返回,如果不为空,栈B直接出栈。
同理:
用两个队列实现一个栈的功能?
<分析>:
入栈:将元素进队列A
出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列;否则将队列A中的元素,依次出队列并放入队列B,直到队列A中的元素只留下一个,然后队列A出队列,再把队列B中的元素出队列依次放入队列A中。
AC代码:
#include<iostream>
#include<stack>
#include<ctime>
using namespace std;
class Solution
{
private:
stack<int> stack1;
stack<int> stack2;
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
int tempVal;
if(stack2.empty()){
while(!stack1.empty()){
tempVal=stack1.top();
stack2.push(tempVal);
stack1.pop();
}
}
tempVal=stack2.top();
stack2.pop();
return tempVal;
}
};
// 以下为测试部分,加入了随机数
/*
int main()
{
Solution sol;
srand((unsigned)time(NULL));
rand();
double feed=((double) rand()/(RAND_MAX)) + 1; // 产生真正的随机数
for(int idx=1;idx<=5;idx++)
{
sol.push(3.24*idx*feed);
}
cout<<sol.pop()<<endl;
cout<<sol.pop()<<endl;
cout<<sol.pop()<<endl;
cout<<sol.pop()<<endl;
cout<<sol.pop()<<endl; // 由于新的队列中没有top()函数,但pop()函数有返回值,故可以如此操作
return 0;
}
*/
另外,有博友用template实现了相关功能: http://blog.csdn.net/xiaofei2010/article/details/8922497
最新文章
- 选中统计winform
- Android自定义View的三种实现方式
- UNIX索引技术访问文件初阶
- ACM 兄弟郊游问题
- Android SDK Tools和Android SDK Platform-tools
- es增量自定义更新的脚本
- struts2配置文件中action的name属性
- C/C++中浮点数格式学习——以IEEE75432位单精度为例
- 在Dubbo中开发REST风格的远程调用(RESTful Remoting)
- Android 微信SDK分享功能中的最全过程步骤分析
- 电脑上已经安装mysql之后安装wamp,wamp中的mysql无法启动的解决办法
- ";windows 正在启动";
- C++ Primer高速学习 第一章 获得二:输入和输出 (IO)
- Delphi在Vasta/win 7下通过UAC控制
- web从入门开始(6)-----框架
- web项目中图标的前端处理方案
- Linux指令--cd,pwd
- 微信小程序 swiper轮播 自定义indicator-dots样式
- AccessTokenValidation3 源码分析 jwttoken验证流程图
- input debounce
热门文章
- ASP.NET MVC4添加区域视图 找到多个与名为“home”的控制器匹配的类型
- DOM生成XML文件
- 【Mybatis】MyBatis之动态SQL(六)
- Scrum冲刺阶段4
- 【Selenium】【BugList9】windows环境,fp = open(";./";+ time.strftime(";%Y-%m-%d %H:%M:%S";) + "; result.html";,&#39;wb&#39;),报错:OSError: [Errno 22] Invalid argument: &#39;./2018-09-05 10:29:32 result.html&#39;
- PHP获取时间戳和微秒数以及生成唯一ID
- enum枚举类
- Day03(黑客成长日记)------>;元祖及列表的增减改查
- forms组件
- input type=&#39;file&#39;文件上传自定义样式