代码随想录第十天|栈与队列理论基础,LeetCode232.用栈实现队列,LeetCode225.用队列实现栈

栈与队列理论基础:

栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。

栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。

所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。

LeetCode232.用栈实现队列

题目链接:232. 用栈实现队列 - 力扣(LeetCode)

思路:

两个栈一个进栈一个出栈来模拟队列的过程

class MyQueue {
public:
    stack<int> in;
    stack<int> out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        //只有当out为空才从in调入数据
        if(out.empty()) {
            //从in导入数据给out
            while(!in.empty()) {
                out.push(in.top());//将in的进栈顺序颠倒过来进out
                in.pop();
            }
        }
        int result = out.top();
        out.pop();
        return result;
    }
    
    int peek() {
        int res = this->pop();//直接调用pop函数
        out.push(res);//pop弹出res数,再把其添加回去
        return res;
    }
    
    bool empty() {
        return in.empty() && out.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

LeetCode225.用队列实现栈

题目链接:225. 用队列实现栈 - 力扣(LeetCode)

思路:

该题可以用一个队列模拟栈,只需要pop时把出的数再添加回队列即可

class MyStack {
public:
    queue<int> in;
    MyStack() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        int  num = in.size() - 1;
        while(num--) {
            in.push(in.front());//队列的front是出,back是入
            in.pop();
        }
        int result = in.front();
        in.pop();
        return result;
    }
    
    int top() {
        return in.back();
    }
    
    bool empty() {
        return in.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值