leetcode-面试题 03.03. 堆盘子

该博客介绍了如何利用C++的vector和stack数据结构实现一个自定义的StackOfPlates类,该类可以处理多个栈,并在栈满时自动创建新栈。push操作会将元素添加到当前未满的栈中,pop操作会从最后一个非空栈弹出元素,popAt则允许指定索引弹出元素。博客详细阐述了每个方法的实现逻辑和边界条件处理。
摘要由CSDN通过智能技术生成

在这里插入图片描述
实现方法:vector+stack
push的时候保证size>0的,然后最后一个没满就直接push,满了就新增。
pop的时候看vector里面空不空,空的话返回-1,不空的话pop最后一个,正好pop完的话就删除这一个。
popAt,看看索引是不是超出去了,超去了返回-1,没超出就pop那个索引对用的栈,pop完的话就删除这个。sts.erase(sts.begin()+index);

class StackOfPlates {
public:
    int size=0;
    vector<stack<int>> sts;
    StackOfPlates(int cap) {
        size=cap;
    }
    
    void push(int val) {
        if(size==0) return ;
        
        if(sts.empty()){
            stack<int> s;
            s.push(val);
            sts.push_back(std::move(s));
            return ;
        }
        if((sts.end()-1)->size()<size){
            (sts.end()-1)->push(val);
        }
        else {
            stack<int> s;
            s.push(val);
            sts.push_back(std::move(s));
        }
    }
    
    int pop() {
        if(sts.empty()) return -1;
        int res=-1;
        if((sts.end()-1)->size()!=0){
            res=(sts.end()-1)->top();
            (sts.end()-1)->pop();
            if((sts.end()-1)->size()==0) 
            sts.pop_back();
        }
        return res;
    }
    
    int popAt(int index) {

        if(sts.size()<=index) return -1;
        int res=sts[index].top();
        sts[index].pop();
        if(sts[index].empty()) sts.erase(sts.begin()+index);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值