0

I am trying to get values from the Linked list.

Can anyone suggest me how to retrieve the values of each node into an array using JS eg: [2,4,7]

ListNode 
{
  val: 2,
  next: ListNode 
        { 
          val: 4, next: ListNode  
                        { 
                           val: 3, next: null 
                        } 
        } 
}
3
  • 2
    Does this answer your question? How to iterate through a linked list in javascript Commented Feb 9, 2020 at 20:11
  • 3
    use a simple while loop or a recursive function Commented Feb 9, 2020 at 20:11
  • iterate and push the val's into your new array Commented Feb 9, 2020 at 20:13

3 Answers 3

1

I hope it helps you:

const res = [];
let curr = list.val;
while (curr) {  // while curr not null
  res.push(curr.val);
  curr = curr.next;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an approach you might take

Iterate through your object until no next is found. Store the values of each node inside the array. Return the array.

list = {
  val: 2,
  next: {
    val: 4,
    next: {
      val: 3,
      next: null
    }
  }
}

function getValues(list) {
  current = list;
  const array = [];
  while (!!current) {
    array.push(current.val);
    current = current.next;
  }
  return array;
}
console.log(getValues(list));

Comments

0

This should be able to solve the problem.

function linkedListToArray(root) {
  let res = [];
  for (let node = root; node !== null; node = node.next) {
    res.push(node.val);
  }
  return res;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.