java 281. Zigzag Iterator(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 281. Zigzag Iterator(#)。java相关的知识,希望对你有一定的参考价值。

public class ZigzagIterator {

    private Iterator<Integer> i, j, tmp;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        i = v2.iterator();
        j = v1.iterator();
    }

    public int next() {
        if (j.hasNext()) { tmp = j; j = i; i = tmp; }
        return i.next();
    }

    public boolean hasNext() {
        return i.hasNext() || j.hasNext();
    }
}
public class ZigzagIterator {
    
    private Queue<Iterator> iterators;
    private int k = 2;
    //private int d = 0;
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        List<List<Integer>> v = new ArrayList<>();
        v.add(v1);
        v.add(v2);
        // iterators = new Iterator<Integer>[k]; // error: generic array creation
        iterators = new LinkedList<>();
        for (int i = 0 ; i < k; i++) {
            if (v.get(i) != null && !v.get(i).isEmpty()) {
                iterators.add(v.get(i).iterator());
            }
        }
    }

    public int next() {
        Iterator cur = iterators.poll();
        int res = (Integer)cur.next();
        if (cur.hasNext()) iterators.offer(cur);
        return res;
    }

    public boolean hasNext() {
        return !iterators.isEmpty();
    }
}

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

以上是关于java 281. Zigzag Iterator(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 281. Zigzag Iterator(#)。java

java 281. Zigzag Iterator(#)。java

java 281. Zigzag Iterator(#)。java

281. Zigzag Iterator

281. Zigzag Iterator - Medium

281. Zigzag Iterator z字型遍历