剑指offer:用两个栈实现队列

题目描述:

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

思路:

可以用stack1来存所有入队的数。在出队操作中,首先将stack1中的元素清空,转移到stack2上,那么此时stack2中的顺序就与队列一致,此时才取出stack2中的栈顶元素。注意,取出元素后,需要将stack2中的数再次清空移回stack1,以保证下次操作的进行。

时间复杂度O(n)。

代码:

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

    int pop() {
        int tmp;
        while(!stack1.empty())
        {
            tmp = stack1.top();
            stack1.pop();
            stack2.push(tmp);
        }
        tmp = stack2.top();
        stack2.pop();
        
        while(!stack2.empty())
        {
            stack1.push(stack2.top());
            stack2.pop();
        }
        
        return tmp;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
原文地址:https://www.cnblogs.com/LJ-LJ/p/10584635.html