Short C++ solution using stack


  • 0
    W
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for(int i=nestedList.size()-1;i>=0;i--)
                s.push(nestedList[i]);
        }
    
        int next() {
            int res = s.top().getInteger();
            s.pop();
            return res;
        }
    
        bool hasNext() {
            while(!s.empty() && !s.top().isInteger()){
                vector<NestedInteger> temp = s.top().getList();
                s.pop();
                for(int i=temp.size()-1;i>=0;i--)
                    s.push(temp[i]);
            }
            return !s.empty();
        }
    
    private:
        stack<NestedInteger>  s;
    };
    
    

Log in to reply
 

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