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?
Using enhanced for loop we can sequentially iterate a LinkedList. The execution of the enhanced for loop ends after we visit all the elements.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With