This question involves writing a function to return the number of nodes in a lin
ID: 3683421 • Letter: T
Question
This question involves writing a function to return the number of nodes in a linked list of integers in two ways: non-reeursively (in) and recursively (in part b). Assume you have been provided the following structure definition and typedefs: struct node { int data; struct node * nextPtr;}; typedef struct code Node; typedef struct code * NodePtr; Write a function that returns the number of nodes in a linked list of integers. Do not use recursion for this part (as you will write the same function using recursion in the next part). int getNumberOfNodes(NodePtr startPtr) {} Write a recursive function that returns the number of nodes in a linked list of integers. You must use recursion for this part. int getNumberOfNodes(NodePtr startPtr)Explanation / Answer
Here is the code for you:
#include <stdio.h>
struct node
{
int data;
struct node * nextPtr;
};
typedef struct node Node;
typedef struct node * NodePtr;
int getNumberOfNodes(NodePtr startPtr)
{
NodePtr temp = startPtr;
int nodeCount = 0;
while(NodePtr != NULL) //For each node.
{
nodeCount++; //Increment the counter.
NodePtr = NodePtr->nextPtr; //Move on to the next node.
}
return nodeCount; //Return the count.
}
int getNumberOfNodes(NodePtr startPtr)
{
if(startPtr == NULL) //If there are no nodes in the list.
return 0; //Return 0.
else
return 1 + getNumberOfNodes(startPtr->nextPtr); //Return 1 + Count the remaining nodes after the current node using the same function.
}
If you need any refinements, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.