Simple concise and clear stack based C++ solution


  • 0
    W
    class NestedIterator {
    private:
        stack<NestedInteger> _S;
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for(auto rit=nestedList.rbegin(); rit != nestedList.rend(); ++rit)
                _S.push(*rit);
        }
    
        int next() {
            hasNext();
            int val = _S.top().getInteger();
            _S.pop();
            return val;
            
        }
    
        bool hasNext() {
            while(!_S.empty()){
                auto el = _S.top();
                if(el.isInteger())
                    return true;
                else{
                    auto l = _S.top().getList();
                    _S.pop();                
                    for(auto rit=l.rbegin(); rit != l.rend(); ++rit)
                        _S.push(*rit);
                }
            }
            return false;
        }
    };
    

Log in to reply
 

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