simple C++ solution


  • 0
    X
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            myvec = flatten(nestedList);
    		idx = 0;
        }
    	//add one utility method to fallten the list in the beginnning
    	vector<int> flatten(vector<NestedInteger> &nestedList){
    	    vector<int> vec;
    		for(NestedInteger nn : nestedList){
    			if(nn.isInteger()) vec.push_back(nn.getInteger());
    			else{
    				vector<int> tmp = flatten(nn.getList());
    				for(int i : tmp){
    					vec.push_back(i);
    				}
    			}
    		}
    		return vec;
    	}
        int next() {
            int result = myvec[idx];
    		idx++;
    		return result;
        }
    
        bool hasNext() {
            return idx < myvec.size();
        }
    private:
    	vector<int> myvec;
    	int idx;
    };
    

Log in to reply
 

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