其他分享
首页 > 其他分享> > 281. Zigzag Iterator z字型遍历

281. Zigzag Iterator z字型遍历

作者:互联网

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 returns false, 
the order of elements returned by next should be: [1,3,2,4,5,6].


不知道怎么去zigzag,想起来就很简单:
j=v1 返回一个值
j=v2 返回一个值
...两个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();
 */
View Code

 

 

标签:hasNext,iterator,Iterator,Zigzag,next,v1,v2,281,ZigzagIterator
来源: https://www.cnblogs.com/immiao0319/p/13737720.html