用两个栈实现队列插入和删除操作

1、题目

用两个栈实现队列的插入和删除操作

2、思路图解

这里写图片描述

class Solution
{
public:
    // 两个栈模拟对列插入
    void push(int node) {
        stack1.push(node);
    }
    // 两个栈模拟对列删除
    int pop() {

        // stack2相关
        if(stack2.empty()){
            while(stack1.size()>0)
            {
                int data = stack1.top();
                stack2.push(data);
                stack1.pop();
            }
        }

        int temp = stack2.top();
        stack2.pop();
        return temp;
    }

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

猜你喜欢

转载自blog.csdn.net/qq_35433716/article/details/81784949