Simple Java Deque solution.


  • 0
    H

    This is very similar to the solutions with Stack. Little logic in Insertion and rest are easy.

    public class NestedIterator implements Iterator<Integer> {
        Deque<NestedInteger> q=new ArrayDeque();
    
        public NestedIterator(List<NestedInteger> nestedList) {
                insert(nestedList, q);
        }
        public void insert(List<NestedInteger> list,Deque<NestedInteger> q){
            for(NestedInteger n: list){
                if( n.isInteger())
                    q.offerLast(n);
                else if(n.getList().size()>0)
                    insert(n.getList(),q);
            }
            
        }
    
        @Override
        public Integer next() {
            
            return q.pollFirst().getInteger();
           
        }
    
        @Override
        public boolean hasNext() {
            return !q.isEmpty();
        }
    }
    

Log in to reply
 

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