0

Why is my count variable not producing the right result?

Expected Output: 15
Actual Output: 0

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}


const a = new Node(2);
const b = new Node(8);
const c = new Node(3);
const d = new Node(-1);
const e = new Node(7);

a.next = b;
b.next = c;
c.next = d;
d.next = e;

const head = a

const sumList = (head) => {
  let count = 0
  sum(head, count)
  return count
}

const sum = (head, count) => {
  if (head === null) return null
  count += head.val
  sum(head.next, count)
}
console.log(sumList(head));

Input is a linked list providing the head of the list -> "1"

  • you need to take the same data structure like the one in the function. please add the real input. – Nina Scholz Jul 27 '22 at 14:05
  • 1
    I tried to make you a snippet. Please fix it to be a [mcve] - for example where does `val` come from in `head.val` – mplungjan Jul 27 '22 at 14:07
  • 1
    The parameter `count` in the `sum` function will be a **copy** of the `count` variable in the `sumList` function. Changing it in `sum()` will have no effect on the `count` in `sumList()`. – Pointy Jul 27 '22 at 14:08
  • @mplungjan Given the recursive nature of the function and the tags, it looks like `list` is expected to be a linked list not an array – Bergi Jul 27 '22 at 14:10
  • list is supposed to be a generator? – Aziz Hakberdiev Jul 27 '22 at 14:11
  • fixed! i came across a similar problem where I had to produce all values in the form of an array. this problem below worked and outputted the correct result. now that I switched the arr to a count it stopped working. – Stack_Overflow Jul 27 '22 at 14:20
  • Can you still please make the snippet work? – mplungjan Jul 27 '22 at 14:27
  • snippet works now! sorry guys, first time using it. – Stack_Overflow Jul 27 '22 at 15:17

0 Answers0