leetcode 225:用队列实现栈

题目:

算法思想:简单的想法是用两个队列,麻烦的操作是移除栈顶元素,用第二个队列作为辅助队列,把第一个队列除了队尾的数据全部放入第二个队列,再拷回第一个队列就行了。本题是用一个队列,思想就是每次插入到队尾,把队列反转一下,那么队首元素一定是栈顶。

代码:

    /** Initialize your data structure here. */
    queue<int> q;
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        int len = q.size();
        while(len > 1)
        {
            int temp = q.front();
            q.pop();
            q.push(temp);
            len--;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int temp = q.front();
        q.pop();
        return temp;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        if(q.size() > 0)
            return false;
        return true;
    }
发布了137 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wh_computers/article/details/100520290