# [LeetCode] Zigzag Iterator

Zigzag Iterator

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

For example, given two 1d vectors:

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

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

1 class ZigzagIterator {
2 private:
3     vector<int> &mv1, &mv2;
4     vector<int>::iterator it1, it2, it;
5 public:
6     ZigzagIterator(vector<int>& v1, vector<int>& v2) : mv1(v1), mv2(v2) {
7         it1 = v1.begin();
8         it2 = v2.begin();
9         it = (it1 == mv1.end()) ? it2 : it1;
10     }
11
12     int next() {
13         int val = *it;
14         if (it == it1) {
15             ++it1;
16             it = (it2 == mv2.end()) ? it1 : it2;
17         } else {
18             ++it2;
19             it = (it1 == mv1.end()) ? it2 : it1;
20         }
21         return val;
22     }
23
24     bool hasNext() {
25         return it1 != mv1.end() || it2 != mv2.end();
26     }
27 };
28
29 /**
30  * Your ZigzagIterator object will be instantiated and called as such:
31  * ZigzagIterator i(v1, v2);
32  * while (i.hasNext()) cout << i.next();
33  */

posted @ 2015-09-14 13:02  Eason Liu  阅读(618)  评论(0编辑  收藏  举报