C++ implementation by @ YYHboost


  • -1
    2
    class ZigzagIterator {
        /** use the pair to record the start iterator and end iterator **/
        queue<pair<vector<int>::iterator, vector<int>::iterator>> Q;
        
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            if(v1.size() != 0) 
                Q.push(make_pair(v1.begin(), v1.end()));
            if(v2.size() != 0)
                Q.push(make_pair(v2.begin(), v2.end()));
        }
        /** this interface can help us to alternatively access the 2 array **/
        /** the idea is just to rolling to pop out the top array and insert the array to the tail **/
        int next() {
            vector<int>::iterator it_start = Q.front().first;
            vector<int>::iterator it_end = Q.front().second;
            /** pop out the current iterator to the sub array **/
            Q.pop();
            /** if the current iterator array is not empty , push the iterator to the tail **/
            if(it_start + 1 != it_end)
                Q.push(make_pair(it_start + 1, it_end));
            return *it_start;
        }
    
        bool hasNext() {
            return !Q.empty();
        }
    };
    
    /**
     * Your ZigzagIterator object will be instantiated and called as such:
     * ZigzagIterator i(v1, v2);
     * while (i.hasNext()) cout << i.next();
     */

Log in to reply
 

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