6ms JAVA Non-recursive fetch one at a time


  • 0
    G
    public class NestedIterator implements Iterator<Integer> {
        
        private final Deque<Iterator<NestedInteger>> nestedListIts = new ArrayDeque<>();
        private Integer next = null;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            if (nestedList != null) {
                nestedListIts.offer(nestedList.iterator());
            }
        }
    
        @Override
        public Integer next() {
            if (hasNext()) {
                final Integer ret = next;
                next = null;
                return ret;
            }
            return null;
        }
    
        @Override
        public boolean hasNext() {
            if (next == null) {
                getNextInt();
            }
            return next != null;
        }
    
        private void getNextInt() {
            while (!nestedListIts.isEmpty()) {
                Iterator<NestedInteger> it = nestedListIts.peekLast();
                if (!it.hasNext()) {
                    nestedListIts.removeLast();
                    continue;
                };
                NestedInteger nInt = it.next();
                if (nInt.isInteger()) {
                    next = nInt.getInteger();
                    return;
                } else {
                    nestedListIts.offerLast(nInt.getList().iterator());
                }
            }
        }
    }
    

Log in to reply
 

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