【问题标题】:Doubly linked list can call a function on each node item?双向链表可以在每个节点项上调用一个函数吗?
【发布时间】:2017-05-19 04:35:07
【问题描述】:

我正在尝试在 LinkedList 构造函数上创建一个方法,该构造函数可以接收一个函数并在每个节点项上调用它。这是我目前所拥有的:

这是我的构造函数:

function LinkedList() {
  this.head = this.tail = null;
}

我有一个我测试过的 addToTail 方法:

LinkedList.prototype.addToTail = function (item) {
  let newNode = new ListNode(item);

  if (this.tail) {
    this.tail.next = newNode;
    newNode.prev = this.tail;
    this.tail = newNode;
  } else {
    this.head = newNode;
    this.tail = this.head;
  }
  return this; 
};

地点:

function ListNode(item, prev, next) {
  this.item = item;
  this.next = next || null;
  this.prev = prev || null;
}

现在我正在尝试在每个节点项上调用一个函数:

LinkedList.prototype.forEach = function (iterator) {
  return this.map(iterator (item))

谁能向我解释为什么我的 forEach 返回一个 []?我也尝试了console.log(this)并且也得到了[]。解决这个问题的最佳方法是什么?谢谢!

【问题讨论】:

  • 向我们展示您如何定义LinkedList.prototype.map。由于您(错误地)在那里转发,所以它返回数组的原因应该很明显。
  • 'item' in iterator(item) 将是未定义的。
  • 我试图使用 Array.prototype.map() 方法。但我只记得我的链表不是数组,所以我现在完全迷路了

标签: javascript data-structures linked-list


【解决方案1】:

也许,这不是最好的解决方案,但是,您可以遍历您的链表并在每个成员上执行函数func

LinkedList.prototype.forEach = function (func) {
  let cur = this.head;
  while (cur) {
    func(cur); // Call your function
    cur = cur.next;
  }
};

或者,如果您想将map 函数添加到您的链接列表中,

LinkedList.prototype.map = function (func) {
  let res = [];
  let cur = this.head;
  while (cur) {
    res.push(func(cur)); // Call your function and add the result
    cur = cur.next;
  }
  return res;
};

然后,您可以调用:

LinkedList.prototype.forEach = function (func) {
  this.map(function (e) { return e; }).forEach(func);
};

【讨论】:

  • 如果您觉得此答案有用,请通过投票或已解决状态向其他人展示。也许,其他人也有类似的问题。
  • 我投了赞成票! :) 对不起,我是一名学生,对 stackoverflow 还是很陌生
  • 谢谢。您可以对答案进行投票,也可以将答案标记为最适合您的问题的答案。欢迎使用 StackOverflow!
猜你喜欢
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2014-12-13
  • 2014-10-13
  • 1970-01-01
相关资源
最近更新 更多