public class ZigzagIterator {
private Iterator<Integer> iter1, iter2;
private Iterator<Integer> iter;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
iter1 = v1.iterator();
iter2 = v2.iterator();
// pay attention here. list1 could be empty
iter = iter1.hasNext() ? iter1 : iter2;
}
public int next() {
int nextInt = iter.next();
if (iter == iter1 && iter2.hasNext()) {
iter = iter2;
} else if (iter == iter2 && iter1.hasNext()) {
iter = iter1;
}
return nextInt;
}
public boolean hasNext() {
return iter.hasNext();
}
}
Follow up: Extend to List of List
List of iterators
- 如果保持所有的 iterators,那么 next() 和 hasNext() can be up to O(n) runtime, n is the size of list of lists. 因为随着 next() 的使用,List of iterators 中会有 iter does not have next.
- 如果只是保持有 next 的 iterators,那么 next() 和 hasNext() 将都是 O(1) runtime. 需要
LinkedList<Iterator<Integer>>
的首个 iter 即为 nextIterator。
public class ZigzagIterator {
private LinkedList<Iterator<Integer>> iterators;
public ZigzagIterator(List<List<Integer>> lists) {
iterators = new LinkedList<>();
for (List<Integer> list: lists) {
if (list != null && !list.isEmpty()) {
iterators.add(list.iterator());
}
}
}
public int next() {
Iterator<Integer> iter = iterators.removeFirst();
int nextInt = iter.next();
if (iter.hasNext()) {
iterators.add(iter);
}
return nextInt;
}
public boolean hasNext() {
return !iterators.isEmpty();
}
}