// Collection is an interface
public interface Collection<E> {
boolean add(E element);
Iterator<E> iterator();
...
}
public interface Iterator<E> {
E next();
boolean hasNext();
void remove();
}
public class MergeIterator {
Iterator<Integer> left;
Iterator<Integer> right;
int lastLeft;
int lastRight;
boolean leftNotUsed;
public MergeIterator (Iterator<Integer> left, Iterator<Integer> right) {
this.left = left;
this.right = right;
if (left.hasNext()) {
lastLeft = left.next();
leftNotUsed = true;
} else if (right.hasNext()) {
lastRight = right.next();
leftNotUsed = false;
}
}
public boolean hasNext() {
return left.hasNext() | right.hasNext();
}
public int next() throws Exception {
if (!left.hasNext() && !right.hasNext()) {
throw new Exception(" ");
}
if (left.hasNext() && !right.hasNext()) {
if (leftNotUsed) {
leftNotUsed = false;
return lastLeft;
}
return left.next();
}
if (!left.hasNext() && right.hasNext()) {
if (leftNotUsed) {
leftNotUsed = false;
return lastLeft;
}
return right.next();
}
if (leftNotUsed) {
lastRight = right.next();
if (lastLeft < lastRight) {
leftNotUsed = false;
return lastLeft;
} else {
return lastRight;
}
} else {
lastLeft = left.next();
if (lastRight < lastLeft) {
leftNotUsed = true;
return lastRight;
} else {
leftNotUsed = false;
return lastLeft;
}
}
}
}
1289

被折叠的 条评论
为什么被折叠?



