Zigzag Iterator(Medium) Z形迭代器

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

For example, given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].

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;
    }
}

References:

1 from Buttercola

2 from segmentfault

3 ZigZag Iterator with m Lists

results matching ""

    No results matching ""