O(1) memory solution


  • 0
    A
    public class NestedIterator implements Iterator<Integer> {
        List<NestedInteger> mList;
        int mIndex;
        NestedIterator mIter;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            mList = nestedList;
            mIndex = 0;
            mIter = null;
        }
    
        @Override
        public Integer next() {
            if (mIter != null) {
                return mIter.next();
            }
            return mList.get(mIndex++).getInteger();
        }
    
        @Override
        public boolean hasNext() {
            if (mIter != null) {
                if(mIter.hasNext()) {
                    return true;
                }
                mIter = null;
                mIndex++;
            }
            while (mIndex < mList.size()) {
                NestedInteger ni = mList.get(mIndex);
                if (ni.isInteger()) {
                    mIter = null;
                    return true;
                }
                mIter = new NestedIterator(ni.getList());
                if (mIter.hasNext()) {
                    return true;
                }
                mIndex++;
            }
            return false;
        }
    }
    

Log in to reply
 

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