Java Solution (6ms, beat 89.2%)


  • 0
    public class NestedIterator implements Iterator<Integer> {
    
        Queue<Integer> q = new LinkedList<>();
    
        public NestedIterator(List<NestedInteger> nestedList) {
            flatten(nestedList); 
        }
    
        @Override
        public Integer next() {
            return q.poll(); 
        }
    
        @Override
        public boolean hasNext() {
            return !q.isEmpty(); 
        }
        
        private void flatten(List<NestedInteger> nestedList){
            if (nestedList == null || nestedList.isEmpty()) return; 
            
           // if it's an integer, then add it to the queue. Otherwise, flatten it. 
            for (NestedInteger o : nestedList){
                if (o.isInteger()) q.offer(o.getInteger()); 
                else flatten(o.getList()); 
            }
            
            return; 
        }
    }
    

Log in to reply
 

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