Himanshu Sourav Himanshu Sourav - 11 days ago 4
C Question

using while in recursive function

to display a linked list, I am using a recursive function. which was running infinite loop thanks to while loop.
when replaced with "if" the program worked without any issues.

looking for expert opinion on usage of


while


inside a recursive function.




recursive function with while

int display(node *curr){
if((curr->next != NULL) ){ //<--replace "if" with "while" and it runs infinite loop
printf("%d :: ",curr->data);
display(curr->next);
}
return 0;
}





complete code with create and display function

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

struct node {
int data;
struct node *next;
};

typedef struct node node;

int create(node *head);
int display(node *head);

int main(int argc, char *argv[]){
int ch,n=0;

node *head,*tail,*current;
head=(node*)malloc(sizeof(node));
create(head);
printf("\n");
display(head);

return 0;
}

int create(node *curr){
int data;
node *next;
printf("Enter the Data Value (Enter -1 to Finish): ");
scanf("%d",&data);
curr->data=data;
if(data == -1)
{
curr->next=NULL;

//return curr;
}
else
{
curr->next=(node*)malloc(sizeof(node));
create(curr->next);
}

return 0; }

int display(node *curr){
if((curr->next != NULL) ){
printf("%d :: ",curr->data);
display(curr->next);
}
return 0; }

Answer

The reason why you cannot use the while(curr->next != NULL) loop to index through and print the list is because for each call of the function display(), the value of curr->next is constant. This seems like it will successfully print the data in your linked list, and then infnitely print the second to last data point, as the comparison for the last data point will continually fail.

as suggested by Ritwick Dey, using

int display(node *curr) 
{ 
    while (curr) 
    {
        printf("%d",curr->data);
        curr = curr->next;
    }
}

should work for you; by changing the pointer of the current node, you modify the conditional of the while loop every iteration. a value of NULL will cause this check to fail, so you can print the final data point without issue. this implementation has the added benefit of avoiding the cost of the recursive function call.

Comments