首页 > 学院 > 开发设计 > 正文

leetcode-225-Implement Stack using Queues

2019-11-08 02:32:46
字体:
来源:转载
供稿:网友

问题

题目:[leetcode-225]

思路

一个实现队列,一个辅助队列。需要注意的是,helper函数需要些两个。处理对尾的情形。

做题的时候别着急,把题看清楚了。 这个题本省我很快可以做完,就是因为看错了queue的接口。所以,别着急。定思路的时候,不在乎那一点时间。

代码

class MyStack {public: /** Initialize your data structure here. */ MyStack() {} /** Push element x onto stack. */ void push(int x) { que1.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { int t = top(); helper(que1, que2); helper1(que2, que1); return t; } /** Get the top element. */ int top() { return que1.back(); } /** Returns whether the stack is empty. */ bool empty() { return que1.empty(); }PRivate: void helper( queue<int>& q1, queue<int>& q2 ){ while(!q1.empty()){ int front = q1.front(); q1.pop(); if(!q1.empty()) q2.push(front); } } void helper1( queue<int>& q1, queue<int>& q2 ){ while(!q1.empty()){ int front = q1.front(); q1.pop(); q2.push(front); } }private: queue<int> que1; queue<int> que2;};/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表