Java 9ms Stack with Iterator


  • 0
    A

    The problem is like deepIterator. We should store iterators in a stack.

    Stack<Iterator<NestedInteger>> s;
    Integer ans = null;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        s = new Stack<>();
        s.push(nestedList.iterator());
        refresh();
    }
    
    private void refresh() {
        ans = null;
        while (!s.isEmpty()) {
            if (!s.peek().hasNext()) {  // iterator is empty. Another situation could be that iterator for the list is empty at all
                s.pop();
                continue;
            }
            NestedInteger curr = s.peek().next();  // get next of top iterator
            if (curr.isInteger()) {
                ans = curr.getInteger();
                return;
            }
            // comes to here, it means it is a list
            s.push(curr.getList().iterator());
        }
    }
    
    @Override
    public Integer next() {
        Integer tmp = ans;
        refresh();
        return tmp;
    }
    
    @Override
    public boolean hasNext() {
        return ans != null;
    }

Log in to reply
 

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