Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to recursively count the number of elements in a linked list in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
  
typedef struct Node {
    int x;
    struct Node *next;
} Node;
 
int count_elements_recursive(Node *root) {
     if (root == NULL) {
        return 0;
    }
    
    return 1 + count_elements_recursive(root->next);
}
   
void add_node(Node **root, int value) {
    Node *new_node = malloc(sizeof(Node));
       
    if (new_node == NULL) {
        puts("malloc error");
        exit(1);
    }
       
    new_node->next = NULL;
    new_node->x = value;
       
    if (*root == NULL) {
        *root = new_node;
        return;
    }
       
    Node *current = *root;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
}
   
void free_LinkedList(Node *root) {
    Node *next;
    while (root != NULL)  {  
        next = root->next;  
        free(root);  
        root = next;  
    }  
}
   
int main() {
    Node *root = NULL;
       
    add_node(&root, 5);
    add_node(&root, 300);
    add_node(&root, 88);
    add_node(&root, 9900);
    add_node(&root, 20);
    add_node(&root, 4);
    add_node(&root, -3);

    printf("%d\n", count_elements_recursive(root));

    free_LinkedList(root);
   
    return 0;
}
   
   
   
   
/*
run:
   
7
   
*/

 



answered Jan 2, 2021 by avibootz
...