Using a loop to move through a linked list

I read about a few basic operations in a linked list, and I saw mostly two types of loops


struct node { int data; struct node *next; }*start=NULL,*tmp; 

The first cycle had the form

 for(tmp=start;tmp->next!=NULL;tmp=tmp->next); 

Using the loop above, now the tmp pointer points to the last node in the list

The second loop had the form

 tmp=start; while(tmp!=NULL) { // do something } 

I think they both do the same job, but I'm not sure. Is there any difference?

+7
source share
4 answers

I suppose your while loop looks something like this.

 temp=start; while(temp!=NULL) { // do something temp= temp->next; } 

In your code for the loop , when you are outside the for loop, temp does not indicate NULL. temp points to the end of the linked list . But in the case of a while loop, your temp points to NULL after exiting the while loop , and you don’t have a tail (unless you have assigned temp to any other temporary variable to change the program logic) with you if you want to use it in further steps. That is the only difference. Except that there is not much difference.

You could test it by writing a small program and print the results. I recommend you do this.

+11
source

The loops are not identical. In fact, your for loop has a problem. Consider what happens when start==NULL before entering a for loop.

 for(tmp=start;tmp->next!=NULL;tmp=tmp->next); 

You assign start to tmp , and then look for tmp , a NULL pointer. I think you need the following instead.

 for(tmp=start;tmp!=NULL;tmp=tmp->next); 

This change makes the for and while tags the same.

+5
source

Q: Effectively no. There are no significant differences; they both do the same job.

You can always code the for () loop with the equivalent of while ().

+1
source

I use a while loop when I need to change a linked list. For example,

 while (root->next) { if(0 == strcmp(root->data,root->next->data)) { temp = root; root = root->next; free(temp) } else { root = root->next; } } 

I use for loop when I need read-only access to a linked list.

0
source

All Articles