The following C structure has been defined: struct int_node { int value: struct
ID: 2247372 • Letter: T
Question
The following C structure has been defined: struct int_node { int value: struct int_node * next: }: Write a function void print _int _list that is given a single argument that is a pointer to a struct int _ node. The function should print the values in the linked of integers indicated by that pointer to the standard output and continue to follow the linked list until a NULL pointer is found. Each integer should be printed as a decimal number, one entry per line. You should not provide the main() function -- only implement the print _ int _ list(struct int _ node * ptr) function as described above.Explanation / Answer
//Iterative version
void print_int_list(struct int_node *ptr)
{
while(ptr!=NULL) // if ptr is null, then this loop will not be executed and the function returns
{
printf("%d ",ptr->value); // printing the value in the node pointed by the ptr
ptr=ptr->next; // ptr will point to the next node
}
return ;
}
// Recursive version
void print_int_list(struct int_node *ptr)
{
if(ptr==NULL) // if the pointer is NULL, that means the list is empty, so nothing to print and hence return
return ;
printf("%d ",ptr->value); // printing the value in the node pointed by the ptr
print_int_list(ptr->next); // now calling the same function with ptr->next
}
I suggest using iterative version because, since it only involves printing the elements in the list, using recursive way consumes stack space. Hence , better use iterative method