Storing only iterators -- C++ code


  • 0
    G
    class ZigzagIterator {
        vector<int>::iterator v1_itr, v2_itr, v1_end, v2_end;
        int turn;
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) :
            v1_itr(v1.begin()), v2_itr(v2.begin()), v1_end(v1.end()), v2_end(v2.end()), turn(0) {}
    
        int next() {
            if (v1_itr == v1_end) return *v2_itr++;
            else if (v2_itr == v2_end) return *v1_itr++;
    
            int ret = (turn == 0 ? *v1_itr++ : *v2_itr++);
            turn ^= 1;
    
            return ret;
        }
    
        bool hasNext() {
            return (v1_itr != v1_end || v2_itr != v2_end);
        }
    };
    

Log in to reply
 

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