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

leetcode-232-Implement Queue using Stacks

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

问题

题目:[leetcode-232]

思路

借助一个辅助栈去实现。把一个栈导入另一个栈,辅助的操作可以写成一个函数。

代码

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