I know the iterative solution is the best way to go, but just to get a some more practice/experience with recursion how would you make a recursive solution to counting nodes in a linked list?
yes I have, I have had the base case as when current->next = NULL, but im really unsure of how to make a function that continues to call itself untill it gets to this base case. Some help would be great, im just really new to recursion!
#include <iostream>
struct Node
{
Node* next;
int payload;
};
Node* head = 0;
int count(Node* p)
{
if (!p)
return 0;
if (!p->next)
return 1;
return 1 + count(p->next);
}
int main()
{
head = new Node;
head->next = new Node;
head->next->next = new Node;
int n = count(head);
std::cout << n << std::endl;
return 0;
}