javascript - JavaScript:无法将第二个值添加到单链表
问题描述
我有以下包含值的数组[8,0,7]
。我想为这些数组值构建一个单链表,按相同的顺序排序。
我ListNode
对链表中的每个节点都有一个对象,其中包含值和next
指向链表中下一个节点的链接。我构建链表的代码目前如下所示:
for(let i=0; i<results.length; i++){
console.log("n:",results[i])
if(!result){
result = new ListNode(results[i])
}else{
console.log("else",results[i])
result.next = new ListNode(results[i]);
}
}
由于某种原因,结果链表只添加7
而不添加0
。
解决方案
如果我理解正确,您希望ListNode
通过单个引用按顺序链接对象,在这种情况下,您需要在每次迭代result
时使用最新ListNode()
附加到链接列表的引用来更新引用:
/* Added to support code snippet */
function ListNode(value) {
this.value = value;
this.next = '';
}
/* Input data */
const results = [8, 0, 7];
/* Track the latest list node appended to the linked list (ie, the head) */
let result = "";
for (let i = 0; i < results.length; i++) {
if (!result) {
result = new ListNode(results[i])
}
else {
result.next = new ListNode(results[i]);
console.log(`${result.value} -> ${result.next.value}`);
/* Update result reference to newly appended list node */
result = result.next
}
}
更简洁地表达此链接过程的另一种方法是通过Array#reduce()
:
/* Added to support code snippet */
function ListNode(value) {
this.value = value;
this.next = '';
}
/* Reduce array to a linked list */
[8, 0, 7].reduce((prev, value) => {
/* Create node for current value */
const node = new ListNode(value);
/* If previous node exists, link it to current node */
if(prev) {
prev.next = node;
console.log(`${prev.value} -> ${node.value}`);
}
/* Return current node which will be the "previous" on
the next iteration */
return node;
}, "");
推荐阅读
- sql - 最佳销售表现者在指定年份的每个月
- php - Centos 8 PHP 56
- javascript - vscode在使用Typescript时如何获取Type Inference Result
- c# - 使用 C# 读取 PDF 表格内容
- arrays - 查询 mongodb 数组字段的更好方法是什么?
- excel - 在第一次计数时添加余数
- c# - 如何捕获特定类型的 InvalidOperationException?
- java - 使用 DTO + 存储过程通过 Spring Hibernate 和 MSSQL 减少模型 @Entity 膨胀
- mongodb - MongoDB 的一个数据库没有响应
- mysql - 如何为从 100 开始并在 MySQL 中递增 5 的数字创建序列?