剑指 5.用两个栈实现队列

链接

题目

在这里插入图片描述

思路

push操作:把数据正常插入到stack1
pop操作:是把stack1中的数据全部导入到stack2中以后再弹出stack2的头部,因此

  • 如果stack2不空就直接弹出stack2的栈顶元素
  • 否则就先把stack1的元素导入过来

模拟一下就清楚了

代码

class Solution {
    
    
public:
    void push(int node) {
    
    
        stack1.push(node);
    }
    int pop() {
    
    
        int ret;
        if (stack2.empty()) {
    
    
            while (!stack1.empty()) {
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
            ret = stack2.top();
            stack2.pop();
        } else {
    
    
            ret = stack2.top();
            stack2.pop();
        }
        return ret;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};

其他

力扣还有用队列实现栈,最好用C写一遍。

猜你喜欢

转载自blog.csdn.net/weixin_44119881/article/details/112238160
今日推荐