在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;
}
}
答案 0 :(得分:2)
所以基本上这就像写一个树的深度优先遍历。该树的叶节点是数字,所有内部节点都被建模为迭代器。这是一些伪代码:
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);
}
}
}
答案 1 :(得分:0)
在这里,我会为你开始:
public <T> Iterator<T> flatten(final Iterator<Iterator<T>> iterators) {
if (iterators == null) {
throw new IllegalArgumentException("iterators can't be null");
}
return new Iterator<>() {
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not implemented: hasNext");
}
@Override
public T next() {
throw new UnsupportedOperationException("Not implemented: next");
}
};
}
现在你只是做那种讨厌的脑力劳动,你就会完成。
修改强>
如果您不习惯这种语法,请稍微简单一点:
public <T> Iterator<T> flatten(final Iterator<Iterator<T>> iterators) {
return new MyFlatteningIterator<>(iterators);
}
public class MyFlatteningIterator<T> implements Iterator<T> {
private final Iterator<Iterator<T>> iterators;
public MyFlatteningIterator(final Iterator<Iterator<T>> iterators) {
if (iterators == null) {
throw new IllegalArgumentException("iterators can't be null");
}
this.iterators = iterators;
}
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not implemented: hasNext");
}
@Override
public T next() {
throw new UnsupportedOperationException("Not implemented: next");
}
}