Java easy solution


  • 0
    F
    private List<Integer> list = new ArrayList<>();
    private int index = 0;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        list.addAll(flat(nestedList));
    }
    
    public List<Integer> flat(List<NestedInteger> list) {
        List<Integer> result = new ArrayList<>();
        for (NestedInteger nestedInteger : list) {
            if (nestedInteger.isInteger()) {
                result.add(nestedInteger.getInteger());
            } else {
                result.addAll(flat(nestedInteger.getList()));
            }
        }
        return result;
    }
    
    @Override
    public boolean hasNext() {
        return index < list.size();
    }
    
    @Override
    public Integer next() {
        return list.get(index++);
    }

Log in to reply
 

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