【DFS】LeetCode 341. 扁平化嵌套列表迭代器

题目链接

341. 扁平化嵌套列表迭代器

思路

遍历 nestedList,碰见子列表便将该子列表传入下一层递归中遍历,直到遍历完所有元素。

代码

class NestedIterator implements Iterator<Integer> {
    ArrayList<Integer> result = new ArrayList<>();
    int index = -1;

    public NestedIterator(List<NestedInteger> nestedList) {
        dfs(nestedList, 0);
    }

    @Override
    public Integer next() {
        this.index++;

        return result.get(index);
    }

    @Override
    public boolean hasNext() {
        return index != result.size() - 1;
    }

    private void dfs(List<NestedInteger> nestedList, int pos){
        if(pos >= nestedList.size()){
            return;
        }

        while(pos < nestedList.size()){
            NestedInteger nestedInteger = nestedList.get(pos);
            if(nestedInteger.isInteger()){
                result.add(nestedInteger.getInteger());
            }else{
                dfs(nestedInteger.getList(), 0);
            }
            pos++;
        }
    }
}
posted @ 2023-02-13 10:53  Frodo1124  阅读(26)  评论(0编辑  收藏  举报