Given two 1d vectors, implement an iterator to return their elements alternately.
Example:
Input: v1 = [1,2] v2 = [3,4,5,6] Output:[1,3,2,4,5,6] Explanation:
By calling next repeatedly until hasNext returnsfalse
,
the order of elements returned by next should be:[1,3,2,4,5,6]
.
思路:
去哪个里面找hasNext()呢?要用一个新的数据结构吧?好像也用不上stack啊
.iterator()这个接口本来就可以直接用
两边其实都可以找next()啊,所以就不知道究竟应该找哪边的。直接i j整个iterator互换就行了
public class ZigzagIterator {
Iterator<Integer> i;
Iterator<Integer> j;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
i = v1.iterator();
j = v2.iterator();
}
public int next() {
if (i.hasNext()) {
Iterator<Integer> temp = i;
i = j;
j = temp;
}
return j.next();
}
public boolean hasNext() {
return (i.hasNext() || j.hasNext());
}
}
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/