Short C++ 16ms using deque


  • 0
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            this->nestedList = &nestedList;
        }
    
        int next() {
            int n = q.front();
            q.pop_front();
            return n;
        }
    
        bool hasNext() {
            while(q.empty() && i < nestedList->size()){
                if((*nestedList)[i].isInteger())
                    q.push_back((*nestedList)[i].getInteger());
                else{
                    NestedIterator* it = new NestedIterator((*nestedList)[i].getList());
                    while(it->hasNext()) q.push_back(it->next());
                }
                i++;
            }
            return !q.empty();
        }
    
    private:
        vector<NestedInteger>* nestedList;
        deque<int>q;
        int i = 0;
    };
    

Log in to reply
 

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