0递归/迭代器/数据结构设计中等 LeetCode341. 扁平化嵌套列表迭代器

该博客介绍了如何实现一个迭代器,用于遍历包含嵌套整数列表的数据结构。通过深度优先搜索(DFS)将嵌套列表扁平化,将所有整数放入一个单一列表,然后使用这个列表创建迭代器。博客提供了具体的Java代码实现,包括NestedIterator类的构造函数、next()和hasNext()方法。这个迭代器使得遍历嵌套整数列表变得简单高效。
摘要由CSDN通过智能技术生成

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

描述

给你一个嵌套的整数列表 nestedList 。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。

实现扁平迭代器类 NestedIterator :

NestedIterator(List nestedList) 用嵌套列表 nestedList 初始化迭代器。
int next() 返回嵌套列表的下一个整数。
boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false 。

分析

容易想到的解法:预先扁平化。
先把所有嵌套的链表扁平化得到一个整数链表,然后由这个整数list得到迭代器,用迭代器实现这两个方法。
扁平化的过程是由当前的嵌套整数链表得到一个迭代器,若当前NestedInteger是整数,则把这个整数加入到最终的整数list中,若当前NestedInteger是链表则递归这个过程。

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return empty list if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class NestedIterator implements Iterator<Integer> {
    List<Integer> li;
    Iterator<Integer> iterator;
    public NestedIterator(List<NestedInteger> nestedList) {
        li = new ArrayList<>();
        dfs(nestedList);
        iterator = li.iterator();
    }

    public void dfs(List<NestedInteger> nestedList){
        Iterator<NestedInteger> iterator = nestedList.iterator();
        while(iterator.hasNext()){
            NestedInteger nestedInteger = iterator.next();
            if(nestedInteger.isInteger()){
                li.add(nestedInteger.getInteger());
            }else{
                dfs(nestedInteger.getList());
            }
        }
    }

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

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

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值