datsenko-md / grokking-algorithms-js

Реализация задач из книги про алгоритмы

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chapter 3, task 2. It is necessary to count a list, not an array.

maxxborer opened this issue · comments

Hello!

In chapter 3 of the book, in problem number 2, which sounds like "Напишите рекурсивную функцию для подсчета
элементов в списке"
, you need to count the number of elements in the list, not in the array.

It is possible that such lists are not often used in JavaScript, but at the same time they are used constantly when building a data tree.

Problem in "grokking-algorithms-js/03_recursion/src/count.js"

Before:

const count = (list) => {
    if (list.length === 0) {
        return 0;
    }
    list.shift();
    return 1 + count(list);
}

export default count;

Solution:

const count = (list) => {
  if (!list.next) return 0;
  return 1 + count(list.next);
}

Example:

const list = {
  next: {
      next: {
          next: {
          },
      },
  },
};
console.log(count(list)); // return 3

image

Just now I discovered that we are not talking about a linked list, but about just a list.
Therefore, it is difficult to say exactly what it is about.