Is there anything wrong with using a queue?


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

    Is there anything wrong with using a queue and loading all the items during the constructor? All the popular solutions have used a stack and did the loading logic in hasNext()/next()


Log in to reply
 

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