Given two 1d vectors, implement an iterator to return their elements alternately.

public class ZigzagIterator {
    private int i1;
    private int i2;
    private List<Integer> v1;
    private List<Integer> v2;
    private boolean even;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        this.v1 = v1;
        this.v2 = v2;

        i1 = 0;
        i2 = 0;
        even = true;
    }

    public int next() {
        if(even) {
            even = !even;
            if(i1 < v1.size()) {
                return v1.get(i1++);
            } else {
                return v2.get(i2++);
            }
        } else {
            even = !even;
            if(i2 < v2.size()) {
                return v2.get(i2++);
            } else {
                return v1.get(i1++);
            }
        }
    }

    public boolean hasNext() {
        return i1 < v1.size() || i2 < v2.size();
    }
}

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i = new ZigzagIterator(v1, v2);
 * while (i.hasNext()) v[f()] = i.next();
 */

results matching ""

    No results matching ""