Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer or a list -- whose elements may also be integers or other lists.
Example 1:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Input: [1,[4,[6]]] Output: [1,4,6] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,4,6]
.
不是展开么,不知道为啥要用next() hasNext()
//这两个函数可能确实没啥用,只是调用一下罢了。
如果是个list,就要add list吗?也不对啊。需要再加一个recursion的函数,让它自己递归
里面用for each循环
iterator不需要初始化
public class NestedIterator implements Iterator<Integer> {
Iterator<Integer> iterator;
List<Integer> flattenedList = new ArrayList();
public NestedIterator(List<NestedInteger> nestedList) {
flatten(nestedList);
iterator = flattenedList.iterator();
}
public void flatten(List<NestedInteger> nestedList) {
for (NestedInteger i : nestedList) {
if (i.isInteger()) {
flattenedList.add(i.getInteger());
}else {
flatten(i.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();
*/