C++ stack of pointers and indexes


  • 0
    Z
    class NestedIterator {
    private:
        vector<int> idx;
        vector<vector<NestedInteger>*> ptrs;
        
        bool search() {
            // return bool: if further search is required
            
            if(ptrs.empty()) {
                return false;
            }
            
            if(idx.back() == ptrs.back()->size()) {
                idx.pop_back();
                ptrs.pop_back();
                return true;
            }
            
            if(ptrs.back()->at(idx.back()).isInteger()) {
                return false;
            }
            
            ptrs.push_back(&(ptrs.back()->at(idx.back()).getList()));
            idx.back()++;
            idx.push_back(0);
            return true;
        }
        
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            ptrs.push_back(&nestedList);
            idx.push_back(0);
        }
        
        int next() {
            int i = ptrs.back()->at(idx.back()).getInteger();
            idx.back()++;
            return i;
        }
    
        bool hasNext() {
            while(search()) {;}
            return not ptrs.empty();
        }
    };
    

    iterator version

    class NestedIterator {
    private:
        vector<vector<NestedInteger>::iterator> iters, ends;
        
        bool search() {
            // return bool: if further search is required
            
            if(iters.empty()) {
                return false;
            }
            
            if(iters.back() == ends.back()) {
                iters.pop_back();
                ends.pop_back();
                return true;
            }
            
            if(iters.back()->isInteger()) {
                return false;
            }
            
            auto& nest_list = iters.back()->getList();
            iters.back()++;
            iters.push_back(nest_list.begin());
            ends.push_back(nest_list.end());
            return true;
        }
        
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            iters.push_back(nestedList.begin());
            ends.push_back(nestedList.end());
        }
        
        int next() {
            int i = iters.back()->getInteger();
            iters.back()++;
            return i;
        }
    
        bool hasNext() {
            while(search()) {;}
            return not iters.empty();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.