【Leetcode】5用两个栈实现一个队列的功能

知识:队列:先进先出,#include<queue>,使用;栈:后进先出#include<stack>,使用

问题:使用两个栈,实现一个队列。

思路:后进:可直接用栈。先出:将stack1里的元素从顶到底放到stack2,完成倒序。再从中拿出。

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

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

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

猜你喜欢

转载自blog.csdn.net/ethan_guo/article/details/81163900