Post

Iterator

Zigzag Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ZigzagIterator {
    private Queue<Iterator<Integer>> q;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        q = new LinkedList<>();
        if (!v1.isEmpty()) {
            q.offer(v1.iterator());
        }
        if (!v2.isEmpty()) {
            q.offer(v2.iterator());
        }   
    }

    public int next() {
        if (hasNext()) {
            Iterator<Integer> curr = q.poll();
            int result = curr.next();
            if (curr.hasNext()) {
                q.offer(curr);
            }
            return result;
        }
        return -1;
    }

    public boolean hasNext() {
        return !q.isEmpty();
    }
}
This post is licensed under CC BY 4.0 by the author.