leetcode-232-Implement Queue using Stacks

来源:互联网 发布:伊辛模型c语言代码 编辑:程序博客网 时间:2024/05/19 03:43

问题

题目:[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(); */
0 0