1. 程式人生 > >【easy】225. Implement Stack using Queues

【easy】225. Implement Stack using Queues

returns for 逆序 object front 簡單 truct clas whether

用隊列實現棧。這個實現方法十分的簡單,就是在push這一步的時候直接變成逆序。

class MyStack {
private:
    queue<int> q;
    queue<int> q2;
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for(int i=0
;i<q.size()-1;i++) { q.push(q.front()); q.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int a = q.front(); q.pop(); return a; } /** Get the top element. */ int
top() { return q.front(); } /** Returns whether the stack is empty. */ bool empty() { return q.empty(); } }; /** * 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();
*/

【easy】225. Implement Stack using Queues