Simple Java solution using queues


  • 0
    A
    public class NestedIterator implements Iterator<Integer> {
        Queue<Integer> queue = new LinkedList<Integer>();
        
        public NestedIterator(List<NestedInteger> nestedList) {
            flatten(nestedList);
        }
        
        void flatten (List<NestedInteger> nestedList) {
            for (NestedInteger n : nestedList) {
                if (n.isInteger())
                    queue.add(n.getInteger());
                else
                    flatten(n.getList());
            }
        }
    
        @Override
        public Integer next() {
            return queue.remove();
        }
    
        @Override
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    }
    

Log in to reply
 

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