# [LeetCode] 281. Zigzag Iterator 之字形迭代器

2021年09月15日 阅读数：1

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

For example, given two 1d vectors:java

```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]`.python

Follow up: What if you are given `k` 1d vectors? How well can your code be extended to such cases?数组

Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for `k > 2` cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:app

```[1,2,3]
[4,5,6,7]
[8,9]
```

It should return `[1,4,8,2,5,9,3,6,7]`.post

Java:code

```public class ZigzagIterator {
List<Iterator<Integer> > iters = new ArrayList<Iterator<Integer> >();

int count = 0;

public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
}

public int next() {
int x = iters.get(count).next();
if(!iters.get(count).hasNext()) iters.remove(count);
else count++;

if(iters.size()!=0) count %= iters.size();
return x;
}

public boolean hasNext() {
return !iters.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:htm

```public class ZigzagIterator {

public Queue<Iterator> queue;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
if (v1.size() != 0) {
queue.offer(v1.iterator());
}
if (v2.size() != 0) {
queue.offer(v2.iterator());
}
}

public int next() {
hasNext();
Iterator it = queue.poll();
int val = (Integer)it.next();
if (it.hasNext()) {
queue.offer(it);
}
return val;
}

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

Python:

```# Time:  O(n)
# Space: O(k)
import collections

class ZigzagIterator(object):

def __init__(self, v1, v2):
"""
:type v1: List[int]
:type v2: List[int]
"""
self.q = collections.deque([(len(v), iter(v)) for v in (v1, v2) if v])

def next(self):
"""
:rtype: int
"""
len, iter = self.q.popleft()
if len > 1:
self.q.append((len-1, iter))
return next(iter)

def hasNext(self):
"""
:rtype: bool
"""
return bool(self.q)

# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())
```

C++:

```class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
v.push_back(v1);
v.push_back(v2);
i = j = 0;
}
int next() {
return i <= j ? v[0][i++] : v[1][j++];
}
bool hasNext() {
if (i >= v[0].size()) i = INT_MAX;
if (j >= v[1].size()) j = INT_MAX;
return i < v[0].size() || j < v[1].size();
}
private:
vector<vector<int>> v;
int i, j;
};
```

C++:

```class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
int n1 = v1.size(), n2 = v2.size(), n = max(n1, n2);
for (int i = 0; i < n; ++i) {
if (i < n1) v.push_back(v1[i]);
if (i < n2) v.push_back(v2[i]);
}
}
int next() {
return v[i++];
}
bool hasNext() {
return i < v.size();
}
private:
vector<int> v;
int i = 0;
};
```

C++: queue

```class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if (!v1.empty()) q.push(make_pair(v1.begin(), v1.end()));
if (!v2.empty()) q.push(make_pair(v2.begin(), v2.end()));
}
int next() {
auto it = q.front().first, end = q.front().second;
q.pop();
if (it + 1 != end) q.push(make_pair(it + 1, end));
return *it;
}
bool hasNext() {
return !q.empty();
}
private:
queue<pair<vector<int>::iterator, vector<int>::iterator>> q;
};
```