7 ms Java solution which I think its easy to understand


  • 0
    A

    public class NestedIterator implements Iterator<Integer> {

    private final Queue<NestedInteger> queue;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        queue = new LinkedList<>();
        for (NestedInteger nested : nestedList) flatten(nested);
    }
    
    @Override
    public Integer next() { 
        return queue.poll().getInteger();
    }
    
    private void flatten(NestedInteger nestedInteger) {
        if (nestedInteger.isInteger()) {
            queue.add(nestedInteger);
            return;
        }
        for (NestedInteger nested : nestedInteger.getList()) flatten(nested);
    }
    
    @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.