what is happening in while loop of linked list traversing program??

struct node
{
int info;
};

``````int main()
{
node a[100];
node *start=&a[1];
int n,i,item;

cout<<"Enter No. of Nodes in Linked List : ";
cin>>n;

cout<<"\nEnter Info of Nodes :\n";
for(i=1;i<=n;i++)
{
cout<<"Node "<<i<<" : ";
cin>>a[i].info;
}

cout<<"\nAfter Traversing : \n";
i=1;
while(start!=0)/* what is happening in this while loop*/
{
cout<<"Node "<<i<<" : "<<a[i].info<<endl;
i++;
}

return 0;
}``````

Let us consider each line step by step. In this code,“start” points to the head or first node of the linked list. The data for this node is stored in info which can be accessed by start->info and a pointer for the next node which can be accessed by start->link.Storing a 0 in the link (for the last node) indicates that it is the last node of the linked list.

while(start!=0) // Check if “start” points to the last node of the linked list. If yes, then exit from loop else continue

{

cout<<“Node”<< i <<":" << a[i].info << endl; //As “start” points to a valid node, print the data stored in this node,

i++; //i is just the node number and has no actual significance in the linked list pointer

start=start->link; //Now the data from this node has been accessed so we make start to point to next node. The address of this is stored in start->link. It is something like i=i+1.

}

1 Like
//