Concise C++ solution using queues


  • 0
    M
    class NestedIterator {
        queue <int> Q;
    public:
        void flatten(NestedInteger &n) {
            if (n.isInteger()) {
                Q.push(n.getInteger());
            } else {
                for (auto x : n.getList()) {
                    flatten(x);
                }
            }
        }
        
        NestedIterator(vector<NestedInteger> &nestedList) {
            for (auto n : nestedList) {
                flatten(n);
            }
        }
    
        int next() {
           int val = Q.front();
           Q.pop();
           return val;
        }
    
        bool hasNext() {
            return !Q.empty();
        }
    };
    

Log in to reply
 

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