225. Implement Stack using Queues
2016-07-05 22:13
281 查看
Implement the following operations of a stack using queues.
1.push(x) – Push element x onto stack.
2.pop() – Removes the element on top of the stack.
3.top() – Get the top element.
4.empty() – Return whether the stack is empty.
方法一:基本思路
跟之前那道反过来的题几乎一样,Implement Queue using Stack, 也就是按照stack的顺序在queue中强行排列,简单直接。
方法二:
换个新思路,方法一增加了push的复杂度。方法二增加了top, pop的复杂度,降低了push。
1.push(x) – Push element x onto stack.
2.pop() – Removes the element on top of the stack.
3.top() – Get the top element.
4.empty() – Return whether the stack is empty.
方法一:基本思路
跟之前那道反过来的题几乎一样,Implement Queue using Stack, 也就是按照stack的顺序在queue中强行排列,简单直接。
class Stack { public: // Push element x onto stack. void push(int x) { queue<int> temp; while (!q.empty()) { //借用temp把queue里新push的值一直调到最顶端 temp.push(q.front()); q.pop(); } q.push(x); while (!temp.empty()) { q.push(temp.front()); temp.pop(); } } // Removes the element on top of the stack. void pop() { q.pop(); } // Get the top element. int top() { return q.front(); } // Return whether the stack is empty. bool empty() { return q.empty(); } private: queue<int> q; };
方法二:
换个新思路,方法一增加了push的复杂度。方法二增加了top, pop的复杂度,降低了push。
class Stack { public: // Push element x onto stack. void push(int x) { while (!q2.empty()) { q1.push(q2.front()); q2.pop(); } q2.push(x);//保持q2中只有一个元素,就是新增的元素。 } // Removes the element on top of the stack. void pop() { top(); q2.pop(); } // Get the top element. int top() { if (q2.empty()) { for (int i = 0; i < q1.size() - 1; i++) { q1.push(q1.front()); q1.pop(); } q2.push(q1.front()); q1.pop(); } 4000 return q2.front(); //q2代表栈顶的元素,如果q2没有,则要在q1最下面把那个元素挑出来放进q2 } // Return whether the stack is empty. bool empty() { return q1.empty() && q2.empty(); } private: queue<int> q1, q2; };
相关文章推荐
- leetcode 232. Implement Queue using Stacks
- How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?
- 232. Implement Queue using Stacks
- iOS开发 纯代码创建UICollectionView 听语音
- 【Android UI】ListView的使用和简单优化
- quick3.3模拟器的横屏
- Junit4出现java.lang.NoSuchMethodError: org.junit.runner.Request.classWithoutSuiteMethod
- Leetcode 51. N-Queens
- UITableView代理cellForRowAtIndexPath不执行的相关解决方案
- poj1776Task Sequences【竞赛图的哈密顿路径】
- [UE4教程] 图形学基础教程01--渲染管线 (带演示程序)
- sqlserver -- 解决sqlserver2008“Prevent saving changes that require table re_creation(阻止保存要求重新创建表的更改)”的问题
- 1443. Printer Queue
- UITableViewHeaderFooterView 特点
- 1002.Anti-prime Sequences
- 导入pullloadmorerecyclerview库出现错误:Please configure your build for VectorDrawableCompat
- leetcode 334. Increasing Triplet Subsequence
- ORA-00054: resource busy and acquire with NOWAIT specified
- MQTT(使用mosquitto做broker)做Android推送部分总结
- Implement Queue using Stacks