178 : counting nodes in a linked list

PHOTO EMBED

Tue May 23 2023 15:17:01 GMT+0000 (Coordinated Universal Time)

Saved by @saakshi #c++

//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
content_copyCOPY