my 32ms C++ solution, using vector<>::iterator


  • 0
    C
    class NestedIterator {
    public:
    	typedef vector<NestedInteger>::const_iterator itertype;
    	NestedIterator(vector<NestedInteger> &nestedList) : iter(nestedList.cbegin()), finaliter(nestedList.cend()), itersNext(), itersEnd(){
    		itersEnd.push(nestedList.cend());
    		firstTime = true;
    	}
    	bool moveIterToInter(){
    		if (iter == finaliter)
    			return false;
    		if (iter == itersEnd.top())
    		{
    			iter = itersNext.top();
    			itersNext.pop();
    			itersEnd.pop();
    			return moveIterToInter();
    		}
    		if ((*iter).isInteger())
    			return true;
    
    		itersNext.push(iter + 1);
    		itersEnd.push((*iter).getList().cend());
    		iter = (*iter).getList().cbegin();
    		return moveIterToInter();
    	}
    	int next() {
    		return (*iter).getInteger();
    	}
    
    	bool hasNext() {
    		if (firstTime){
    			firstTime = false;
    		}
    		else
    			iter++;
    		return moveIterToInter();
    	}
    private:
    	itertype iter, finaliter;
    	stack<itertype> itersNext, itersEnd;
    	bool firstTime;
    };
    

Log in to reply
 

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