C++ implementation using iterator (can extend to k)


  • 0
    T
    class ZigzagIterator {
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            it1=v1.begin();
            it2=v2.begin();
            end1=v1.end();
            end2=v2.end();
            cur=1; //record which vector to be processed next
        }
    
        int next() {
           int res;
           if(cur==1&&it1!=end1){res=*it1;++it1;cur=2; }
           else if(cur==2&&it2!=end2){res=*it2;++it2;cur=1;}
           else if(it2==end2){res=*it1;++it1;cur=1;}
           else {res=*it2;++it2; cur=2;}
           return res;
        }
    
        bool hasNext() {
           return it1!=end1||it2!=end2;
        }
    private:
    vector<int>::iterator it1,it2,end1,end2;
    int cur;
    
    };

Log in to reply
 

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