[LintCode] Problem 540 - Zigzag Iterator

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

Example

No.1

Input: v1 = [1, 2] and 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].

No.2

Input: v1 = [1, 1, 1, 1] and v2 = [3, 4, 5, 6]

Output: [1, 3, 1, 4, 1, 5, 1, 6]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private Queue<Iterator> queue = new LinkedList<>();

public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
if (!v1.isEmpty())
queue.offer(v1.iterator());

if (!v2.isEmpty())
queue.offer(v2.iterator());
}

public int next() {
Iterator iterator = queue.poll();
int next = (int) iterator.next();

if (iterator.hasNext())
queue.offer(iterator);

return next;
}

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