【剑指Offer笔记】:用两个栈实现队列

解题思路

先进后出,再来一次先进后出,就变成后进先出了

include

include

include

using namespace std;

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

int pop()
{
    int val = -1;

    if (stack1.empty() && stack2.empty())
    {
        return -1;
    }

    if (stack2.empty())
    {
        while (!stack1.empty())
        {
            stack2.push(stack1.top());
            stack1.pop();
        }
    }

    //stack2现在就是队列了
    val = stack2.top();
    stack2.pop();

    return val;
}

private:
stack stack1;
stack stack2;
};
int main()
{
Solution solu;
solu.push(1);
solu.push(2);
solu.push(3);
solu.push(4);

int node;

cout << solu.pop() << endl;
cout << solu.pop() << endl;
cout << solu.pop() << endl;
cout << solu.pop() << endl;

cout << system("pause");
return 0;

}

牛客网在线检验:用两个栈实现队列


参考资料:http://blog.csdn.net/gatieme/article/details/51112580

你可能感兴趣的:(【剑指Offer笔记】:用两个栈实现队列)