C++ Non-recursive standard stack solution


  • 0
    A

    Nothing special I guess.

    class NestedIterator {
    protected:
        stack<pair<vector<NestedInteger>&, uint>> k;
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            k.emplace(nestedList, 0);
        }
    
        int next() {
            return k.top().first[k.top().second++].getInteger();
        }
    
        bool hasNext() {
            while (!k.empty()) {
                vector<NestedInteger>& n = k.top().first;
                uint i = k.top().second;
                if (i >= n.size()) {
                    k.pop();
                    if (!k.empty()) k.top().second++;
                } else if (n[i].isInteger()) return true;
                else k.emplace(n[i].getList(), 0);
            }
            return false;
        }
    };
    

Log in to reply
 

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