C++ solution using stack of iterators, easy to understand and concise


  • 0
    A
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            s.push({nestedList.begin(), nestedList.end()});
        }
    
        int next() {
            return (s.top().first++)->getInteger();
        }
    
        bool hasNext() {
            while (!s.empty()) {
                if (s.top().first == s.top().second) {
                    s.pop();
                    if (!s.empty())
                        ++s.top().first;
                }
                else if (s.top().first->isInteger())
                    return true;
                else
                    s.push({s.top().first->getList().begin(), s.top().first->getList().end()});
            }
            return false;
        }
        
    private:
        stack<pair<vector<NestedInteger>::iterator, vector<NestedInteger>::iterator>> s;
    };

Log in to reply
 

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