每日一题——栈实现队列,队列实现栈
来源:互联网 发布:洛枳扮演者晁然淘宝店 编辑:程序博客网 时间:2024/06/05 02:00
1,用两个栈实现队列
2,用两个队列实现栈
栈->队列思路:入队时,直接往stack1压入元素; 出队时,判断stack2是否有元素,有则直接弹出栈顶元素,没有则将stack1中的元素一一压入stack2,再弹出stack2的栈顶元素。class MyQueue {public: stack<int> stack1; stack<int> stack2; MyQueue() { // do intialization if necessary } void push(int element) { // write your code here stack1.push(element); } int pop() { // write your code here if(stack2.empty()) { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } int ret = stack2.top(); stack2.pop(); return ret; } else { int ret = stack2.top(); stack2.pop(); return ret; } } int top() { // write your code here if(stack2.empty()) { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } return stack2.top(); } else return stack2.top(); }};
队列->栈思路:有两个队列,一个用来进出栈的,另一个是中转站。入栈时,直接往queue1放进元素;出栈时,先将queue1中前count-1个元素依次放进queue2,然后将最后一个元素出队列。class MyStack {public: queue<int> queue1; queue<int> queue2; MyStack() { // do intialization if necessary } void push(int element) { // write your code here queue *pushtmp; if(!IsQueueEmpty(queue1)) { pushtmp = queue1; } else { pushtmp = queue2; } EnQueue(pushtmp, element); } int pop() { // write your code here int ret; queue* pushtmp; queue* tmp; if(!IsQueueEmpty(queue1)) { pushtmp = queue1; tmp = queue2; } else { pushtmp = queue2; tmp = queue1; } if(IsQueueEmpty(pushtmp)) { cout<<stack is empty<<endl; } while(SizeOfQueue(pushtmp)!=1) { EnQueue(tmp,DeQueue(pushtmp)); } ret = DeQueue(pushtmp); return ret; }
阅读全文
0 0
- 每日一题——栈实现队列,队列实现栈
- 每日一练——用两个栈实现队列&用两个队列实现栈
- 每日一题(36) - 用两个栈实现队列
- 每日一题(37) - 两个队列实现栈
- 每日一题之队列与栈的相互实现
- 每日一题(33)——用两个栈实现一个队列的功能?要求给出算法和思路
- 用栈实现队列(每日一道算法题)
- 栈与队列【每日一题】
- 每日一省————链表之队列的简单实现
- 每日一省————使用二叉堆实现优先队列
- 数据结构算法代码实现——栈和队列(一)
- 每日编程15之用二个队列实现栈数据结构
- 队列(一)——队列的数组实现方式
- 队列实现栈和栈实现队列
- 栈实现队列&&队列实现栈
- 栈实现队列,队列实现栈
- 队列实现栈,栈实现队列
- 数据结构--队列实现栈&栈实现队列
- 使用Jmeter进行接口测试和压力测试的配置和使用
- Redis-AOF持久化
- Codeforces Round #421 A. Mister B and Book Reading
- Web 请求过程
- Github没有记录Contributions的原因及解决方案
- 每日一题——栈实现队列,队列实现栈
- 使用Ansible部署Nginx
- Spring源码(一) 源码转换eclipse工程
- 【Java Utility】Jsoup网页爬虫工具--设置Element的HTML内容【十二】
- Codeforces Round #422 A. I'm bored with life
- mysql学生选课
- 【JavaScript的条件操作符】
- 探索ES6 Iterator(遍历器)
- 栈的应用