【问题标题】:Javascript Nested array flatten with Iterator and hasnext and next implementationJavascript嵌套数组用Iterator和hasext和next实现展平
【发布时间】:2019-02-26 23:43:42
【问题描述】:

** 尝试实现一个类,它有两个方法 next 和 hasNext 我能够在 C++ 和 Java 中找到类似的实现,但不是 Javascript 任何 hep 将不胜感激**


class NestedIterator {
  constructor() {}

hasNext() {
   //Todo
  }

  next() {
    //Todo
   }
}

var list;
var iterator;

/* Should print
 * 2
 * 4
 * 6
 */
list = [2, [4, [6]]];
iterator = new NestedIterator(list);
while (iterator.hasNext()) {
  console.log(iterator.next());
}`

【问题讨论】:

  • 您是否要求 Javascript 中的链接列表?

标签: javascript algorithm iterator


【解决方案1】:

这种方法先将数组展平,然后在展平后的数组上循环。

class NestedIterator {
  constructor(list) {
    this.list = [];

    let flat = (arr, index) => {
      if (index === arr.length) return;
      
      if (Array.isArray(arr[index])) flat(arr[index], 0);
      else this.list.push(arr[index]);
      
      flat(arr, ++index);
    }

    this.index = 0;
    flat(list, 0);
    this.length = this.list.length;
  }

  hasNext() {
    return this.index < this.length;
  }

  next() {
    if (this.hasNext()) return this.list[this.index++];
    else return null; // maybe an error.
  }
}

var list;
var iterator;

/* Should print
 * 2
 * 4
 * 6
 */
list = [2, [4, [6]]];
iterator = new NestedIterator(list);
while (iterator.hasNext()) {
  console.log(iterator.next());
}

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2021-10-20
    • 2021-07-12
    • 2015-06-28
    • 1970-01-01
    • 2015-03-14
    • 2019-12-21
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多