341. 扁平化嵌套列表迭代器

发布时间 2023-11-30 15:46:53作者: CrossAutomaton

341. 扁平化嵌套列表迭代器

2021年3月23日

没有代码提示的我快死了

就是个遍历……只要知道函数和方法就没什么难度

注意尝试迭代,不要用递归

class NestedIterator {
private:
    int curInteger;
    stack<pair<vector<NestedInteger>::iterator, vector<NestedInteger>::iterator>> st;

public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        st.emplace(nestedList.begin(),nestedList.end());
    }
    
    int next() {
        return curInteger;
    }
    
    bool hasNext() {
        while(!st.empty()){
            auto &i=st.top();
            if(i.first==i.second){
                st.pop();
                continue;
            }
            if(i.first->isInteger()){
                curInteger=i.first->getInteger();
                i.first++;
                return true;
            }
            auto &lit=i.first->getList();
            st.emplace(lit.begin(),lit.end());
            i.first++;
        }
        return false;
    }
};