Recursive Java Solution


  • 0
    A
    public class NestedIterator implements Iterator<Integer> {
        private List<Integer> resultList;
        private int idx;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            this.resultList = new ArrayList<>();
            this.flattenList(nestedList);
            this.idx = 0;
        }
    
        @Override
        public Integer next() {
            if (this.hasNext() == false) { return -1; }
            int res = resultList.get(idx);
            idx ++;
            return res;
        }
    
        @Override
        public boolean hasNext() {
            if (resultList == null || idx >= resultList.size()) {
                return false;
            }
            return true;
        }
        
        private void flattenList (List<NestedInteger> list) {
            int listIdx = 0;
            while (listIdx != list.size()) {
                if (list.get(listIdx).isInteger()) {
                    NestedInteger curr = list.get(listIdx);
                    resultList.add (curr.getInteger());
                }
                else {
                    flattenList (list.get(listIdx).getList());
                }
                listIdx ++;
            }
        }
    }
    

Log in to reply
 

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