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

时间:2017-05-19 04:35:08

标签: 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(这个)并且还得到了[]。什么是最好的方法来解决这个问题?谢谢!

1 个答案:

答案 0 :(得分: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);
};