在 Java 中展平迭代器的迭代器。如果输入是 [ [1,2], [3,[4,5]], 6],它应该返回 [1,2,3,4,5,6]。实现 hasNext() 和 next()。当内部迭代器或列表为空时要小心。 我认为我的代码不适用于多级内部列表。
public class FlattenList {
int index = 0; // keep an index to indicate where the current accessed element is
List<Integer> flattenedList = new ArrayList<>(); // flattenedList
public FlattenList(List<List<Integer>> lists){
for(List<Integer> list : lists){ // add all inner list to our underlying list.
flattenedList.addAll(list);
}
}
public boolean hasNext(){ // check if the index has exceeded the list size
return flattenedList.size() > index? true : false;
}
public Integer next(){ // return the next element, and increment the index
Integer result = flattenedList.get(index);
index++;
return result;
}
}
最佳答案
所以基本上这就像编写树的深度优先遍历。这棵树的叶子节点是数字,所有内部节点都被建模为迭代器。这是一些伪代码:
void flatten(Iterator<Object> iterator, List<Integer> flattenedList) {
for (Object o : iterator) {
if (o instanceof Iterator) {
flatten((Iterator) o, flattenedList);
} else {
flattenedList.add((Integer) o);
}
}
}
关于java - 在 Java 中展平迭代器的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21977718/