Reputation: 11
The following is the structure
struct list *node
{
int data;
struct list *next;
}
What does node=node->next exactly do while traversing the linked list and isn't the next element pointer to pointer in the node variable?
Upvotes: 1
Views: 2707
Reputation: 2612
Imagine incrementing a variable with a while
loop.
int i = 0;
while (i < 6) {
// this loop will run forever without the line below
i++; // adds one to i so the loop will not run infinitely
}
The concept is the same with linked lists:
while (node != NULL) {
//need to make sure this loop doesn't run forever
node = node->next // kind of like incrementing i
}
Now the while loop will run until the end of the list is reached.
Upvotes: 2
Reputation: 142
node = node->next makes node point towards next pointer in linked list. As the value stored in next is pointer to next element in the list. So making node as node->next and then calling the function again or iterating in the for loop makes you go forward. Hope that helps
Upvotes: 1