给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的项或者为一个整数,或者是另一个列表。
/**
* // 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 null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class NestedIterator implements Iterator<Integer> {
List<Integer> list;
Iterator<Integer> iterator;
public NestedIterator(List<NestedInteger> nestedList) {
list = new LinkedList<Integer>();
add(nestedList,list);
iterator = list.iterator();
}
@Override
public Integer next() {
return iterator.next();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
public void add(List<NestedInteger> nestedList, List<Integer> list){
for(NestedInteger nest : nestedList){
if(nest.isInteger()){
list.add(nest.getInteger());
}else{
add(nest.getList(),list);
}
}
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
来源:CSDN
作者:皓月v
链接:https://blog.csdn.net/qq_36198826/article/details/104011224