Super short and elegant! 20 lines!


  • 0
    K
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            helper(nestedList);
            pos = -1;
        }
        
        void helper(vector<NestedInteger> &nestedList) {
            for (auto &nest_integer_ : nestedList) {
                if (nest_integer_.isInteger()) container.push_back(nest_integer_.getInteger());
                else helper(nest_integer_.getList());
            }
        }
        
        int next() {
            return container[++pos];
        }
    
        bool hasNext() {
            return pos + 1 != container.size();
        }
        vector<int> container;
        int pos;  
    };
    

Log in to reply
 

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