Leetcode 281 Solution

This article provides solution to leetcode question 281 (zigzag-iterator)

https://leetcode.com/problems/zigzag-iterator

Solution

class ZigzagIterator {
    queue<pair<vector<int>::iterator, vector<int>::iterator>> q;

public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        if (v1.empty() == false)
            q.push(make_pair(v1.begin(), v1.end()));

        if (v2.empty() == false)
            q.push(make_pair(v2.begin(), v2.end()));
    }

    int next() {
        auto pair = q.front();
        q.pop();

        auto it = pair.first;
        auto end = pair.second;
        int res = *it++;

        if (it != end)
            q.push(make_pair(it, end));

        return res;
    }

    bool hasNext() {
        return q.empty() == false;
    }
};

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i(v1, v2);
 * while (i.hasNext()) cout << i.next();
 */