【代码随想录训练营】day11 栈和队列

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

我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下的底层结构。SGI STL中 队列底层实现缺省情况下一样使用deque实现的。

deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。

std::stack<int, std::vector<int> > third;  // 使用vector为底层容器的栈
std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列

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

正常初始化

stack<int> stack_in;
stack<int> stack_out;

232.用栈实现队列

#include <iostream>
class MyQueue {
public:
    stack<int> stack_in;
    stack<int> stack_out;

    MyQueue() {


    }
    
    void push(int x) {
        stack_in.push(x);
    }
    
    int pop() {
        // 方法1
        // if (stack_out.empty()){
        //     while (!stack_in.empty()){
        //         stack_out.push(stack_in.top());
        //         stack_in.pop();
        // }            
        // }

        // int res = stack_out.top();
        // stack_out.pop();
        // return res;

        // 方法2, 调用peek
        int res = peek();
        stack_out.pop();
        return res;
    }
    
    int peek() {
        if (stack_out.empty()){
            while (!stack_in.empty()){
                int top_num = stack_in.top();
                stack_in.pop();
                stack_out.push(top_num);
        }}
        return stack_out.top();

        // 方法2, 实现pop后调用pop
        // int res = pop();
        // stack_out.push(res); //push back
        // return res;

    }
    
    bool empty() {
        return (stack_in.empty()) && (stack_out.empty());
    }
};

时间复杂度: push和empty为O(1), pop和peek为O(n)
空间复杂度: O(n)

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值