207k views
4 votes
Write a recursive algorithm that calculates and returns the
length of a list in C++.

User Klikerko
by
8.5k points

1 Answer

1 vote

Final answer:

A recursive algorithm to calculate the length of a list in C++ involves a function that returns 0 for an empty list or 1 plus the length of the rest of the list for non-empty lists.

Step-by-step explanation:

To write a recursive algorithm that calculates and returns the length of a list in C++, we'll define a function that calls itself with a subset of the list until it reaches the end. The base case for our recursion will be when the function reaches a null pointer or the end of the list, in which case it returns 0. From there, each recursive call adds 1 to the result of the recursive call with the next element in the list.

Here's an example algorithm:

int listLength(ListNode* head) {
// Base case: If the list is empty (i.e., the head is null),
// the length is 0.
if (head == nullptr) return 0;
// Recursive case: Otherwise, the length is 1 plus the
// length of the rest of the list.
return 1 + listLength(head->next);
}

Please note that ListNode is an assumed struct or class that has a member called next which points to the next element in the list. When using this function, ensure that the list ends with a null pointer to avoid infinite recursion.