Google – Iterator of Iterator
Input一个list of iterator,设计一个SuperIterator。
[Solution]
Maintain一个current iterator
Read full article from Google – Iterator of Iterator
Input一个list of iterator,设计一个SuperIterator。
[Solution]
Maintain一个current iterator
class
SuperIterator<T>
implements
Iterator<T> {
List<Iterator<T>> itList;
Iterator<T> curr;
int
i;
public
SuperIterator(List<Iterator<T>> itList) {
if
(itList ==
null
|| itList.isEmpty()) {
throw
new
IllegalArgumentException();
}
this
.itList = itList;
curr = itList.get(
0
);
}
@Override
public
boolean
hasNext() {
return
curr !=
null
&& curr.hasNext();
}
@Override
public
T next() {
T result;
if
(curr !=
null
&& curr.hasNext()) {
result = curr.next();
}
else
{
while
(i < itList.size() && !itList.get(i).hasNext()) {
i++;
}
if
(i < itList.size()) {
curr = itList.get(i);
}
else
{
return
null
;
}
result = curr.next();
}
// update curr iterator
while
(i < itList.size() && !itList.get(i).hasNext()) {
i++;
}
if
(i < itList.size()) {
curr = itList.get(i);
}
else
{
curr =
null
;
}
return
result;
}
}