write recursive function that calculates and returns the len

write recursive function that calculates and returns the length of a linked list

Solution

// C code to determine length of linked list recursively

#include <stdio.h>
#include <stdlib.h>

// node of linked list
struct node
{
int key;
struct node* next;
};

// push key to linked list
void push(struct node** root, int new_element)
{
struct node* nodeNew = (struct node*) malloc(sizeof(struct node));
nodeNew->key = new_element;
nodeNew->next = (*root);
(*root) = nodeNew;
}

// recursively get length of linked list
int lengthLinkedlist(struct node* root)
{
// base case
if (root == NULL)
return 0;

// recursively call the function
return 1 + lengthLinkedlist(root->next);
}


int main()
{
struct node* root = NULL;

push(&root, 11);
push(&root, 34);
push(&root, 4);
push(&root, 23);
push(&root, 14);
push(&root, 88);
push(&root, 56);
push(&root, 84);
push(&root, 6);


/* Check the count function */
printf(\"Length of Linked list: %d\ \", lengthLinkedlist(root));
return 0;
}


/*
output:

Length of Linked list: 9

*/

write recursive function that calculates and returns the length of a linked listSolution// C code to determine length of linked list recursively #include <st
write recursive function that calculates and returns the length of a linked listSolution// C code to determine length of linked list recursively #include <st

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site