两个栈实现队列
来源:互联网 发布:创世数据网站 编辑:程序博客网 时间:2024/06/11 19:59
看面经的时候发现,有道两个栈实现队列的题目,我的第一反应就是,这就是多此一举。恩,这就是考对栈和队列的熟悉程度的。
栈和队列的操作都是常数级的,所以先入为主,两个栈实现的队列也应该是常数级的,可是想来想去发现实现不了(也可能是我没想到=。=),目前的方法就是来回倒栈,时间复杂度就是长度。
现用C简单的写了一下,数组实现的,是那个意思就行了。
#include<cstdio>#include<iostream>#include<cstring>using namespace std;int a[400],a_top;int b[400],b_top;void add(int x){ a[a_top++]=x;}int get(){ int &l=a_top,&index=b_top; cout<<l<<" "<<index<<endl; if(l==0) { cout<<"queue is null"<<endl; return 0; } while(--l) { b[index++]=a[l]; } int x=a[l]; int &z=b_top,&zz=a_top; while(z--) { a[zz++]=b[z]; } z++; return x;}int main(){ memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); a_top=b_top=0; add(1); add(2); add(3); add(4); add(5); cout<<get()<<endl; add(6); cout<<get()<<endl; cout<<get()<<endl; cout<<get()<<endl; cout<<get()<<endl; cout<<get()<<endl; cout<<get()<<endl; return 0;}
0 0
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个 栈 实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 队列--两个栈实现
- 两个队列实现栈
- FFmpeg浅尝辄止(四)——音频的解码和编码
- windows 10(64位)下实现vs20120C++调用matlab r2014a编写的m文件生成的.dll,.lib,.h文件
- HTTP 的那些事
- Handler,Looper&&在异步线程中更新UI
- dubbo与spring mvc 整合 搭建
- 两个栈实现队列
- 详解Linux运维工程师必备技能
- PHP日期和时间处理
- 微信对话框BaseAdapter的实现
- 数据的网络请求
- java 实现word 转PDF (采用第三方技术 IText、Poi、Jsoup)
- 前端工程筹建NodeJs+gulp+bower
- 面向对象设计的SOLID原则
- 运维工程师必须掌握的基础技能有哪些?