面试题 03.03. 堆盘子

面试题 03.03. 堆盘子

输入:
["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"]
[[2], [1], [2], [3], [0], [0], [0]]

“StackOfPlates” [2] 表示每堆盘子最高2个,再次push就要另添加一个栈来放盘子

"push" [1] 堆盘子1(第一堆有一个盘子1)

"push" [2] 堆盘子2(第一堆有两个盘子1,2)

"push" [3] 堆盘子3(第一堆已经有两个盘子了,达到_capcity,另起一堆,第二堆有一个盘子3)

“popAt” [0] 弹出指定堆(第一堆)的顶层盘子2

“popAt” [0] 弹出指定堆(第一堆)的顶层盘子1(此时第一堆没有盘子了,记得删除这一堆,原来的第二堆变成现在的第一堆)

“popAt” [0] 弹出指定堆(第一堆)的顶层盘子3

注意cap=0的时候。

class StackOfPlates {
public:
    vector<stack<int> > v;
    int stack_max_size;
    StackOfPlates(int cap) {
        v.clear();
        stack_max_size = cap;
    }
    
    void push(int val) {
        int v_size = v.size();
        if(v_size==0 || v.back().size()==stack_max_size){
            stack<int> s;
            s.push(val);
            v.push_back(s);
        }
        else v.back().push(val);
    }
    
    int pop() {
        int v_size = v.size();
        if(v_size==0 || stack_max_size==0) return -1; 
        int res = v.back().top();
        v.back().pop();
        if(v.back().size()==0) v.pop_back();
        return res;
    }
    
    int popAt(int index) {
        int v_size = v.size();
        if(index>=v_size || stack_max_size==0) return -1;
        int res = v[index].top();
        v[index].pop();
        if(v[index].size()==0)  v.erase(v.begin()+index);
        return res;
    }
};
发布了248 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38603360/article/details/105157949