user3351630
user3351630

Reputation: 11

what does node=node->next mean in linked list (data structures)

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

Answers (2)

MortalMan
MortalMan

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

DarkCoderRises
DarkCoderRises

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

Related Questions