javascript - 双向链表可以在每个节点项上调用一个函数吗?

标签 javascript data-structures linked-list

我正在尝试在 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) 也得到了 []。解决这个问题的最佳方法是什么?谢谢!

最佳答案

也许,这不是最好的解决方案,但是,您可以遍历链表并在每个成员上执行函数 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);
};

关于javascript - 双向链表可以在每个节点项上调用一个函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061538/

相关文章:

javascript - 如何使用 Ajax 将对象数组发送到 PHP 并更新 MySQL 服务器

python - python3中两个排序链表的交集?

Java/实现链表

java - 了解家庭作业

java - Groovy:以 Maps 作为键的 MultiValueMap

java - 如何删除字符串中的 HTML 元素?

javascript - 你能在不使用 ' or "引号的情况下创建 JavaScript 字符串吗?

javascript - 如何迭代 JSON 数据并添加单独的 CSS?

java - 并发HashMap : remove on condition

java - Clojure:从 ArrayMap 到 HashMap 的转换