C++ solution using iterator list


  • 0
    S
    class ZigzagIterator {
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            vec_end = {v1.end(), v2.end()};
            itl = {v1.begin(), v2.begin()};
        }
    
        int next() {
            int ret = *(itl[idx]);
            ++itl[idx];
            idx = (idx+1)%count;
            return ret;
        }
    
        bool hasNext() {
            int ct = 0;
            while (itl[idx]==vec_end[idx] && ct<count) {
                idx = (idx+1)%count; ++ct;
            }
            return !(ct==count);
        }
    private:
        int idx = 0;
        int count = 2;
        vector<vector<int>::iterator> vec_end;
        vector<vector<int>::iterator> itl;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.