2

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.

2
  • you're setting .next of the same thing each time through the loop. try changing your array to [ 8, 0, 7, 3 ] . what happens then? Commented Feb 13, 2020 at 5:12
  • Could you explain you intent little more clearly? Like what exactly you are trying to achieve? Commented Feb 13, 2020 at 5:27

1 Answer 1

3

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;
  
}, "");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.