Javascript version, the same logic as the top answer


  • 0
    T
    /**
     * @constructor
     * @param {Integer[]} v1
     * @param {Integer[]} v1
     */
    var ZigzagIterator = function ZigzagIterator(v1, v2) {
        this.queue = [];
        
        if (v1 && v1.length > 0) {
            this.queue.push([v1, 0]); 
        }
        if (v2 && v2.length > 0) {
            this.queue.push([v2, 0]); 
        }
    };
    
    
    /**
     * @this ZigzagIterator
     * @returns {boolean}
     */
    ZigzagIterator.prototype.hasNext = function hasNext() {
        return this.queue.length > 0;
    };
    
    /**
     * @this ZigzagIterator
     * @returns {integer}
     */
    ZigzagIterator.prototype.next = function next() {
        var [v, pos] = this.queue.shift(),
            result = v[pos];
        
        // advance pos
        pos++;
        if (pos < v.length) {
            this.queue.push([v, pos]);
        }
        
        return result;
    };
    

Log in to reply
 

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