Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4038

JavaScript: Can't add second value to singly linked list

I have the following array containining values [8,0,7]. I would like to build a singly linked list for these array values, that is sequenced in the same order.

I have a ListNode object for each node in the linked list, which contains the value and a next link to the next node in the linked list. My code for building the linked list currently looks like this:

   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]);
        }
    }

For some reason the result linked list adds only 7 and not 0.

Upvotes: 2

Views: 61

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

If I understand correctly, you're wanting to sequentially link ListNode objects by a single reference, in which case you'll need to update the result reference with the most recent ListNode() appended to the linked list, per iteration:

/* 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
  }
}

 

Another way to express this linking process more concisely would be via 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;
  
}, "");

Upvotes: 3

Related Questions