My Java AC Solution


  • 0
    S
    public class NestedIterator implements Iterator<Integer> {
    
        NestedIterator nextNested; //if it is nested list
        Iterator<NestedInteger> iter;
        Integer next;
        public NestedIterator(List<NestedInteger> nestedList) {
            iter = nestedList.iterator();
            next = nextR(); //get next and save it to next;
            
        }
        
        public Integer nextR() {
            
            if(nextNested!=null){
                if(nextNested.hasNext()){  //nested still has more
                    return nextNested.next(); 
                } else {
                    nextNested = null;  ///otherwise set it to null
                }
            }
            if(!iter.hasNext()) return null;
            while(iter.hasNext())  //this will handle empty nestedlist in a row like [[],[]]
            {
                NestedInteger ni = iter.next();
                if(ni.isInteger()) return ni.getInteger();
                nextNested=new NestedIterator(ni.getList());
                Integer re= nextNested.next();
                if(re!=null) return re;
            }
            return null;
        }
        
    
        @Override
        public Integer next() {
            if(next==null) return null;
            int n = next;
            next = nextR();
            return n;
        }
    
        @Override
        public boolean hasNext() {
            return next!=null;
        }
    }
    

Log in to reply
 

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