首页 > 解决方案 > 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

标签: javascriptsingly-linked-list

解决方案


如果我理解正确,您希望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;
  
}, "");


推荐阅读