Suppose you have a Iterator class with has_next()
and get_next()
methods.
Please design and implement a ZigzagIterator class as a wrapper of two iterators.
For example, given two iterators:
i0 = [1,2,3,4]
i1 = [5,6]
ZigzagIterator it(i0, i1); while(it.has_next()) { print(it.get_next()); }
The output of the above pseudocode would be [1,5,2,6,3,4]
.
Note: For Java solution we will use JDK's Iterator class, so the methods would be hasNext()
and next()
.
public class ZigzagIterator {
Iterator i0, i1;
Iterator it;
public ZigzagIterator(Iterator i0, Iterator i1) {
this.i0 = i0; this.i1 = i1;
this.it = i0.hasNext()? i0:i1;
}
public boolean has_next() {
return it.hasNext();
}
public int get_next() {
int val = (Integer)it.next();
if(it == i0 && i1.hasNext())
it = i1;
else if(it == i1 && i0.hasNext())
it = i0;
return val;
}
}
第二种解法,这个方便解有多个Iterator的情况,也就是followup的问题:
class ZigzagIterator {
private:
vector<Iterator> vec;
vector<Iterator>::iterator it;
public:
ZigzagIterator(Iterator& i0, Iterator& i1) {
vec = {i0, i1};
it = vec.begin();
while(!(*it).has_next()) it++;
}
bool has_next() {
return (*it).has_next();
}
int get_next() {
auto prev = it;
int val = (*it).get_next();
do {
if(++it == vec.end())
it = vec.begin();
} while(!(*it).has_next() && it != prev);
return val;
}
};