描述
给你一个嵌套的整数列表 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();
*/