Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using loop to traverse through linked list

Tags:

c

I was reading about a few basic operations on linked list and I saw two types of loops being used predominantly


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

The first loop was of the form

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

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

The second loop was of the form

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

I think that both of them do the same work, but I'm not sure. Is there any difference?

like image 600
OneMoreError Avatar asked Jul 13 '12 02:07

OneMoreError


People also ask

Can you use a for loop to traverse a linked list?

Using enhanced for loop we can sequentially iterate a LinkedList. The execution of the enhanced for loop ends after we visit all the elements.

How do I traverse in LinkedList?

An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element.

What is the fastest way to traverse a linked list?

Unrolled linked lists are another way of making linked lists faster. The main idea behind unrolled linked lists is to store more than one value in a single linked list node. An unrolled linked list with up to 4 values in each node. In the above example, the list stores 4 elements in a single node.

How do you use a while loop in a linked list?

The assignment current = current. next assigns the next field in current as equal to current itself. In this way, on every iteration of the while loop, current becomes its next node and the list is traversed (as long as a valid node is contained in current 's next field. The key idea is that current = current.


1 Answers

I suppose your while loop is something like this.

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

In your code of for loop, When you are out of the for loop, temp is not pointing to NULL. temp is pointing to end of the linked list. But in case of while loop, your temp is pointing to NULL after you exit the while loop and you don't have tail(Unless you assign temp to any other temporary variable to change the logic of program) with you if you want to use it in the further steps. That is the only difference. Except that there isn't much difference.

You could have checked it by writing a small program and printing the results. I recommend you do it.

like image 194
Sandeep Avatar answered Oct 11 '22 07:10

Sandeep