【LeetCode225】Implement Stack using Queues

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

1、这里只使用了一个queue,相比较于使用两个queue更快;

2、所有容器都有size(),empty();

3、vector和queue有明显的前后,所以可以用front()和back();

4、stack用top();

5、stack和queue是适配器,没有迭代器;

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/87966311