LeetCode-225 用队列实现栈

版权声明:本文为博主原创文章,但是欢迎转载! https://blog.csdn.net/yancola/article/details/87896837

用一个队列实现栈,主要是在pop和top时,先把队列前面的size-1个元素移到队列尾部,再对对头元素进行操作。

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

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/yancola/article/details/87896837