Java Solution using Queue without pre-processing, average O(1) time


  • 0
    public class NestedIterator implements Iterator<Integer> {
        
        Queue<Integer> q = new LinkedList<Integer>();
        List<NestedInteger> list;
        int index = 0;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            list=nestedList;
        }
    
        @Override
        public Integer next() {
            return q.poll();
        }
    
        @Override
        public boolean hasNext() {
            if(q.peek()!=null)return true;
          
            while(index<list.size()){
                NestedInteger tem = list.get(index);index++;
                if(tem.isInteger())q.offer(tem.getInteger());
                else{
                    NestedIterator it = new NestedIterator(tem.getList());
                    while(it.hasNext())q.offer(it.next());
                }
                if(q.peek()!=null)return true;
            }
            return false;
        }
    }
    

Log in to reply
 

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