首页 > 解决方案 > 链表。对代码中的平等问题感到困惑

问题描述

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

  list.addToTail = function(value) {
    var node = Node(value);
    if (list.head === null) {
      //have to equal list.tail = list.head because you want them pointing to the same object
      list.tail = list.head = Node(value);
    } else {
      list.tail.next = node;
      list.tail = node;
    }
  };
return list;
};

var Node = function(value) {
  var node = {};

  node.value = value;
  node.next = null;

  return node;
};

我有一个简单的问题。我正在构建一个链接列表,我对.addToTail我所构建的属性有一个特殊的问题。上面的当前代码可以按我想要的方式工作和执行。两部分问题。如果我为if/else语句编写这样的代码:

  if (list.head === null) {
    list.tail = node;
    list.head = node;
  } else {
    list.tail.next = Node(value);
    list.tail = Node(value);
  }

即使我分别设置和相同的值,我的if声明也不起作用。仅当我像在原始代码中那样使它们在一行中彼此相等时才有效。我不明白这里有什么区别。它们是相同的值,那么为什么单独编写它不起作用?另外,在我的声明中;如果我将和的值设置为. 这不能正常工作,但替换为确实可以像在原始代码中一样工作。tailheadlist.tail = list.head = nodeelselist.tail.nextlist.tailNode(value)Node(value)var node = Node(value)

第一个代码块正确地给了我我的节点列表: head: { value: 4, next: { value: 5, next: [Object] } }. 第二个代码块给了我:head: { value: 4, next: { value: 5, next: null }}它没有next正确设置尾部的 value 属性。这到底是怎么回事?我错过了什么吗?这两个代码块应该是等价的

标签: javascriptdata-structures

解决方案


当你这样做时

    list.tail.next = Node(value);
    list.tail = Node(value);

您可以创建两个节点实例

在哪里

      list.tail.next = node;
      list.tail = node;

只创建一个


推荐阅读