JAVA solution using a queue (easily understand)


  • 0
    T
    public class NestedIterator implements Iterator<Integer> {
        //In construction method, this program converts given nestedInteger sequence to a queue recursively
        Queue<Integer> q = new LinkedList<Integer>();
        public NestedIterator(List<NestedInteger> nestedList) {
            openList(nestedList);
        }
        
        public void openList(List<NestedInteger> nestedList){
            for(NestedInteger list : nestedList){
                if(list.isInteger() ){
                    q.add(list.getInteger() );
                }
                else{
                    openList(list.getList());
                }
            }
        }
    
        @Override
        public Integer next() {
            return q.poll();
        }
    
        @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.