JavaScript Generator solution


  • 0
    B
    function* flatten(arr) {
      for(let v of arr.getList()) {
        if (v.isInteger(v)) yield v;
        else yield* flatten(v);
      }
    }
    
    /**
     * @constructor
     * @param {NestedInteger[]} nestedList
     */
    var NestedIterator = function(nestedList) {   
      this.gen = flatten(nestedList);
      this.queue = [];
    };
    
    /**
    * @this NestedIterator
    * @returns {boolean}
    */
    NestedIterator.prototype.hasNext = function() {
      if (this.queue.length) return true;
      let {done, value} = this.gen.next();
      if (!done) {
        this.queue.push(value);
        return true;
      }
      return false;
    };
    
    /**
    * @this NestedIterator
    * @returns {integer}
    */
    NestedIterator.prototype.next = function() {
      if (this.queue.length) {
        return this.queue.shift();
      }
      return this.gen.next().value;
    };
    
    

Log in to reply
 

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