Simple C++ solution using vector<int>


  • 0
    Z
    class NestedIterator {
    private:
        vector<int> v;
        int pos,size;
    public:
        void myhelper(vector<int>& v,vector<NestedInteger>& nestedList){
    
            for(int i=0;i<nestedList.size();i++){
                if(nestedList[i].isInteger())
                    v.push_back(nestedList[i].getInteger());
                else if(!nestedList[i].getList().empty())
                    myhelper(v,nestedList[i].getList());
    
            }
        }
        NestedIterator(vector<NestedInteger> &nestedList) {
            pos=-1;
            myhelper(v,nestedList);
            size=v.size();
        }
    
        int next() {
            return v[pos];
        }
    
        bool hasNext() {
            if(pos<size-1){
                pos++;
                return true;
            }
            return false;
        }
    };

  • 0

    Nice, but no need to pass in v in the function signature for myhelper.


Log in to reply
 

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