Using Java Deque


  • 0
    A
    import java.util.NoSuchElementException;
    
    public class NestedIterator implements Iterator<Integer> {
    
        private Deque<NestedInteger> deque;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            deque = new LinkedList<>(nestedList);
        }
    
        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Empty iterator");
            }
    
            NestedInteger current = deque.pollFirst();
            int result = current.getInteger();
            return result;
        }
    
        @Override
        public boolean hasNext() {
            NestedInteger current = deque.peekFirst();
            while (!deque.isEmpty() && !current.isInteger()) {
                deque.pollFirst();
    
                List<NestedInteger> currentList = current.getList();
                for (int i = currentList.size() - 1; i >= 0; i--) {
                    deque.addFirst(currentList.get(i));
                }
    
                current = deque.peekFirst();
            }
    
            return !deque.isEmpty();
        }
    }
    

Log in to reply
 

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