[栈] leetcode 341 Flatten Nested List Iterator

problem:https://leetcode.com/problems/flatten-nested-list-iterator/

        这道题要手动维护栈,对于弱鸡的我写起来真痛苦Orz

class NestedIterator {
public:
    vector<NestedInteger> list;
    NestedIterator(vector<NestedInteger> &nestedList) {
        list = nestedList;
        if(nestedList.size() != 0)
            sta.push({0, &list});
    }
    stack<pair<int,vector<NestedInteger>*>> sta;
    int data;
    int next() {
        return data;
    }
    
    void advance()
    {
        if(sta.size() == 0) return;
        sta.top().first++;
        
        while(!sta.empty() && sta.top().first >= sta.top().second->size())
        {
            sta.pop();
            if(!sta.empty()) sta.top().first++;
        }        
    }
    
    bool hasNext()
    {
        if(sta.size() == 0) return false;
        auto& cur = *sta.top().second;
        int idx = sta.top().first;
        if(cur[idx].isInteger())
        {
            data = cur[idx].getInteger();
            advance();
            return true;
        }
        else
        {
            if(cur[idx].getList().size() > 0) 
            {
                sta.push({0, &cur[idx].getList()});
                if(hasNext()) return true;
            }
            advance();
            return hasNext();     
        }       
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11291579.html