Clean c++ solution


  • 0

    Use a stack to keep track iterator of vectors

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

Log in to reply
 

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