share my solution with stack.


  • 0
    Y
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for (auto ptr = nestedList.rbegin(); ptr != nestedList.rend(); ++ptr) {
                stk_.push(*ptr);
            }
        }
    
        int next() {
            return next_;
            
        }
    
        bool hasNext() {
            if (stk_.empty()) return false;
            auto t = stk_.top();
            stk_.pop();
            while (!t.isInteger()) {
                const vector<NestedInteger>& tmp = t.getList();
                for (int k = tmp.size() - 1; k >= 0; --k) {
                    stk_.push(tmp[k]);
                }
                if (stk_.empty()) return false;
                t = stk_.top();
                stk_.pop();
            }
            next_ = t.getInteger();
            return true;
        }
        stack<NestedInteger> stk_; 
        int next_;
    };
    

Log in to reply
 

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