[LeetCode]Implement Stack using Queues
2015-07-19 11:42
369 查看
解题思路:
1,跟Implement Queue using Stacks这道题类似;
2,用两个Queue,一个叫Queue1,一个叫Queue2。
3,对于top或者pop操作,把当前存数据的那个Q1前n-1个elem都转移到另外一个Q2,只剩下最后一个elem,也就是最新push进的。
4,对于push来说,如果Q1和Q2都为空,那么随便找一个添加elem。然后,必须保证Q1和Q2至少有一个为空
5,不能单纯的通过size=1来判断这个queue是不是要top的queue
6,通过 queueToPush() 和 emptyQueue() 这两个helper方法,找到数据搬迁是from哪里to哪里
//编译错误
Line 21: ‘class std::queue<int>’ has no member named ‘top’
Line 18: ‘from’ declared as reference but not initialized
引用类型定义时要赋值;
能不用指针就不用指针;
1,跟Implement Queue using Stacks这道题类似;
2,用两个Queue,一个叫Queue1,一个叫Queue2。
3,对于top或者pop操作,把当前存数据的那个Q1前n-1个elem都转移到另外一个Q2,只剩下最后一个elem,也就是最新push进的。
4,对于push来说,如果Q1和Q2都为空,那么随便找一个添加elem。然后,必须保证Q1和Q2至少有一个为空
5,不能单纯的通过size=1来判断这个queue是不是要top的queue
6,通过 queueToPush() 和 emptyQueue() 这两个helper方法,找到数据搬迁是from哪里to哪里
//编译错误
Line 21: ‘class std::queue<int>’ has no member named ‘top’
Line 18: ‘from’ declared as reference but not initialized
引用类型定义时要赋值;
能不用指针就不用指针;
class Stack { public: // Push element x onto stack. void push(int x) { queue<int> & q = queueToPush(); q.push(x); } // Removes the element on top of the stack. void pop() { queue<int> & from = queueToPush(); queue<int> & to = emptyQueue(); transport(from, to); from.pop(); } // Get the top element. int top() { queue<int> & from = queueToPush(); queue<int> & to = emptyQueue(); transport(from, to); int ret = from.front(); to.push(ret); from.pop(); return ret; } // Return whether the stack is empty. bool empty() { return q1.empty() && q2.empty(); } queue<int>& queueToPush(){ return q1.empty() ? q2 : q1; } queue<int>& emptyQueue(){ return q1.empty() ? q1 : q2; } void transport(queue<int> &from, queue<int> &to){ while (from.size() > 1){ int temp = from.front(); to.push(temp); from.pop(); } } private: queue<int> q1; queue<int> q2; };
相关文章推荐
- ZOJ 1926 Guessing Game
- HDU 2604 Queuing
- 转:抗锯齿方法两种(其一:paint.setAntiAlias(ture);paint.setBitmapFilter(true))
- Linking different libraries for Debug and Release builds in Cmake on windows?
- OpenCV Access pixel value
- 使用Fuel安装OpenStack juno之一安装Fuel Master
- 数据的刷新(UITableViewCell实现点击单元格弹窗更改数据)
- UITableView性能优化(复用池的使用原理)
- iOS切换到UiScrollView界面卡死
- 图片轮播器(UIScrollView-UIPageControl)
- 解决“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- 炫酷的AndroidUI库集合
- POJ 1947 Rebuilding Roads (树形DP)
- UITextView 不左上角显示
- 汤姆猫程序(UIImageView动画)
- Gitlab 上Iisues 使用以及代码管理
- UIView相对坐标转换
- ${pageContext.request.contextPath} JSP取得绝对路径
- poj1649 Rescue(BFS+优先队列)
- UIPopoverController和UIActionSheet在iPad中使用