javascript - 链表。对代码中的平等问题感到困惑
问题描述
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
声明也不起作用。仅当我像在原始代码中那样使它们在一行中彼此相等时才有效。我不明白这里有什么区别。它们是相同的值,那么为什么单独编写它不起作用?另外,在我的声明中;如果我将和的值设置为. 这不能正常工作,但替换为确实可以像在原始代码中一样工作。tail
head
list.tail = list.head = node
else
list.tail.next
list.tail
Node(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 属性。这到底是怎么回事?我错过了什么吗?这两个代码块应该是等价的
解决方案
当你这样做时
list.tail.next = Node(value);
list.tail = Node(value);
您可以创建两个节点实例
在哪里
list.tail.next = node;
list.tail = node;
只创建一个
推荐阅读
- r - 如何从excel开始为elrm创建成功/试验次数格式的数据框
- c++ - 开发插件时指定正确的#include 标头
- javascript - 应用我为数组的每个元素创建的方法
- azure - 将 bak 文件还原到 Azure SQL PAAS 数据库?
- swift - 使用未解析的标识符“Form”
- c++ - 加速简单 Eigen 程序的基本方法
- influxdb - 如何查询所有 InfluxDB _internal 数据库测量?
- android - 如何修复工作不正常的工作经理类?
- delphi - 如何从 Delphi 执行 WSL
- angular - Angular 库导出了一些意想不到的类