My C++ solution - easy to understand!!!


  • 0
    E
    class ZigzagIterator {
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            nums1 = v1;
            nums2 = v2;
            first = nums1.begin();
            second = nums2.begin();
            mark = false;
        }
    
        int next() {
            int val;
            if(mark) {
                val = *first;
                ++first;
            }
            else {
                val = *second;
                ++second;
            }
            return val;
        }
    
        bool hasNext() {
            if(first == nums1.end() && second == nums2.end()) {
                return false;
            }
            else if(first == nums1.end() || second == nums2.end()) {
                mark = first == nums1.end() ? false : true;
                return true;
            }
            else {
                mark = !mark;
                return true;
            }
        }
    private:
        vector<int> nums1;
        vector<int> nums2;
        vector<int>::iterator first;
        vector<int>::iterator second;
        bool mark;
    };

Log in to reply
 

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