剑指offer两个栈实现队列的c++写法(九度1512)
来源:互联网 发布:mac 桌面图标 编辑:程序博客网 时间:2024/05/13 05:51
用两个栈(Stack)实现一个队列(Queue)
方法如下:
入队时,将元素压入s1。出队时,判断s2是否为空,如不为空,则直接弹出s2栈顶元素;如为空,则将s1的元素逐个“倒入”s2,把s2栈顶元素弹出。这种方法即简单实现队列。效率较高。
代码:
#include <stdio.h>#include <stack>#include <string.h>#include <stdlib.h>using namespace std;int main(){int n,pushn;char a[5];stack<int> s1;stack<int> s2;scanf("%d",&n);while(n>0){scanf("%s",a);if(!strcmp(a,"PUSH")){scanf("%d",&pushn);//printf("this is a push operation!n is %d\n",pushn);s1.push(pushn);}else if(!strcmp(a,"POP")){//printf("this is a pop operation!");if(s2.empty())//如果栈为空{//printf("----------s2 is empty\n");//system("pause");if(s1.empty()) printf("-1\n");else{int k=s1.size();int popn;//printf("----------s1 is not empty,s1 size is %d\n",k);//system("pause");while(k>0){s2.push(s1.top());s1.pop();k--;}printf("%d\n",s2.top());s2.pop();}}else{//s2栈不为空printf("%d\n",s2.top());s2.pop();}}n--;}//system("pause"); return 0;}
- 剑指offer两个栈实现队列的c++写法(九度1512)
- 【剑指Offer面试编程题】题目1512:用两个栈实现队列--九度OJ
- [九度OnlineJudge][剑指Offer]题目1512:用两个栈实现队列
- 【剑指Offer面试题】 九度OJ1512:用两个栈实现队列
- 剑指offer题解C++【5】用两个栈实现队列
- [九度1512 剑指offer7] 用两个栈实现队列
- 剑指offer(C++)——用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 【剑指offer】两个栈实现一个队列
- 【剑指offer】两个队列实现一个栈
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指offer 两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- ON_COMMAND_RANGE 多个按钮响应一个函数
- android开发
- android dp,sp,px
- 虚函数(续)
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- 剑指offer两个栈实现队列的c++写法(九度1512)
- JavaScript execCommand
- 位域 unsigned char a:4;
- ServletContext 问题
- VS2012中安装XNA方法
- iOS7适配遇到的一些问题
- QMovie跳转到指定帧
- (Android) Broadcast Intent Permissions
- mdadm + RAID 阵列