LeetCode341(2021.3.23)

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

class NestedIterator implements Iterator<Integer> {
    private List<Integer> list; //列表
    private Iterator<Integer> cur; //迭代器

    public NestedIterator(List<NestedInteger> nestedList) {
        list = new ArrayList<Integer>();
        dfs(nestedList);
        cur = list.iterator();
    }

    private void dfs(List<NestedInteger> nestedList) {
        for (NestedInteger nest : nestedList) {
            if (nest.isInteger()) {
                list.add(nest.getInteger());
            }
            else {
                dfs(nest.getList());
            }
        }
    }

    @Override
    public Integer next() {
        return cur.next();
    }

    @Override
    public boolean hasNext() {
        return cur.hasNext();
    }
}

留下评论