Recursion Java Solution


  • 0
    Q
    public class NestedIterator implements Iterator<Integer> {
        private List<Integer> mList;
        private int index;
        private int mSize;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            index = 0;
            mList = new ArrayList<>();
            parse(nestedList);
        }
        
        private void parse(List<NestedInteger> nestedList) {
            for (NestedInteger i : nestedList) {
                if (i.isInteger()) {
                    mList.add(i.getInteger());
                    mSize++;
                } else {
                    List<NestedInteger> list = i.getList();
                    if (!list.isEmpty()) parse(list);
                }
            }
        }
    
        @Override
        public Integer next() {
            int v = mList.get(index);
            index++;
            return v;
        }
    
        @Override
        public boolean hasNext() {
            return index < mSize;
        }
    }
    

Log in to reply
 

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