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

解题思路

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

include <iostream>

include <vector>

include <stack>

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<int> stack1;
stack<int> 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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容