My C++ solution using the real iterator


  • 0
    A
    /**
     * // This is the interface that allows for creating nested lists.
     * // You should not implement it, or speculate about its implementation
     * class NestedInteger {
     *   public:
     *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
     *     bool isInteger() const;
     *
     *     // Return the single integer that this NestedInteger holds, if it holds a single integer
     *     // The result is undefined if this NestedInteger holds a nested list
     *     int getInteger() const;
     *
     *     // Return the nested list that this NestedInteger holds, if it holds a nested list
     *     // The result is undefined if this NestedInteger holds a single integer
     *     const vector<NestedInteger> &getList() const;
     * };
     */
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            current = nestedList.begin();
            end = nestedList.end();
            current2 = nullptr;
        }
    
        int next() {
            int value;
            
            if (current2 == nullptr) {
                value = current->getInteger();
                current++;
                
            } else {
                value = current2->next();
                if (!current2->hasNext()) {
                    delete current2;
                    current2 = nullptr;
                    current++;
                }
            }
            
            return value;
        }
    
        bool hasNext() {
            while (current2 == nullptr) {
                if (current == end) {
                    return false;
                }
                
                if (current->isInteger()) {
                    return true;
                }
                
                current2 = new NestedIterator(current->getList());
                if (current2->hasNext()) {
                    return true;
                }
                
                delete current2;
                current2 = nullptr;
                current++;
            }
            
            return current2->hasNext();
        }
        
    protected:
        vector<NestedInteger>::iterator current, end;
        NestedIterator *current2;
    };
    
    /**
     * Your NestedIterator object will be instantiated and called as such:
     * NestedIterator i(nestedList);
     * while (i.hasNext()) cout << i.next();
     */
    

Log in to reply
 

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