剑指offer 面试题9 用两个栈实现队列

问题:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

输入:两个栈

输出:队列的push和pop操作

思路:

入队列时,压进stack1。

出队列时,判断stack2是否为空:

  • 如果为空,则将stack1全部元素弹出,压入stack2,
  • 如果不为空,则从stack2弹出一个元素。

代码:

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        int result;
        if(!stack2.empty())
        {
            result = stack2.top();
            stack2.pop();
        }
            
        else
        {
            int temp;
            while(!stack1.empty())
            {
                temp = stack1.top();
                stack1.pop();
                stack2.push(temp);
            }
            if(!stack2.empty())
            {
                result=stack2.top();
                stack2.pop();
            }
            else
                return -1;
        }
        return result;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

复杂度分析:时间复杂度为O(n),空间复杂度也为O(n).

发布了56 篇原创文章 · 获赞 10 · 访问量 6801

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/104350345