用两个栈实现队列

  • 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
  • 设置两个栈s1,s2
    • 进栈只进s1
    • 出栈只从s2出,如果s2不为空,则按序出栈即可;如果发现s2为空,则把s1的所有数据按出栈顺序进入到s2即可
  • C++ 代码
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

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

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