//code for finding number of nodes in a given linked list: recursive
int count(struct Node *p){
int c=0;
while(p!= 0) {
c++;
p=p->next;
}
return c;
}
// O(n) time complexity and O(1) space complexity
//recursive function for counting number of nodes in a given linked list
int count(struct Node *p){
if(p==0)
return 0;
else
return count(p->next)+1;
}
// addition will be done at the time of returning.
// time complexity : O(n)
//space complexity : O(n) for stack as it includes recursion
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter