ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

扁平化嵌套列表迭代器

2026/9/18 13:24:18 拓冰建站 浏览量
扁平化嵌套列表迭代器

题目链接

扁平化嵌套列表迭代器

题目描述


注意点

  • 每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表
  • 嵌套列表中的整数值在范围 [-1000000, 1000000] 内
  • NestedInteger中有三个方法,分别是:isInteger() ,判断当前存储的对象是否为 int;getInteger() , 如果当前存储的元素是 int 型的,那么返回当前的结果 int,否则调用会失败;getList() ,如果当前存储的元素是 List<‘NestedInteger’> 型的,那么返回该 List,否则调用会失败

解答思路

  • 由于列表的元素也可能是整数或者是其他列表,所以先使用递归将迭代器中的列表都伸展开来加入到list中,其中list中的元素都是整数
  • next和hasnext相当于遍历list的过程

代码

/*** // 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> {private List<Integer> list = new ArrayList<>();private int index;public NestedIterator(List<NestedInteger> nestedList) {add(nestedList);}private void add(List<NestedInteger> nestedList) {for (NestedInteger nestedInteger : nestedList) {if (nestedInteger.isInteger()) {list.add(nestedInteger.getInteger());} else {add(nestedInteger.getList());}}}@Overridepublic Integer next() {return list.get(index++);}@Overridepublic boolean hasNext() {return index < list.size();}
}/*** Your NestedIterator object will be instantiated and called as such:* NestedIterator i = new NestedIterator(nestedList);* while (i.hasNext()) v[f()] = i.next();*/

关键点

  • 理解本题中NestedIterator和NestedInteger结构