Home > Back-end >  Can someone explain this While loop in a linked list to me?
Can someone explain this While loop in a linked list to me?

Time:08-05

I'm confused with this while loop statement while creating a linked list: while(curr->next != NULL) But curr->next will always be NULL since we never initialized curr->next to point to anything, so that while loop should never run!

Can someone explain this, please?? The code snippet is as follows:

    if (head != NULL)
    {
        curr = head;
        while(curr->next != NULL)
        {
            curr = curr->next;
        }

        curr->next = n;
    }

The complete code is shown below:

void AddNode(int addData)
{
    nodePtr n = new node;
    n->next = NULL;
    n->data = addData;

    if (head != NULL)
    {
        curr = head;
        while(curr->next != NULL)
        {
            curr = curr->next;
        }

        curr->next = n;
    }
    else
    {
        head = n;
    }
}

CodePudding user response:

curr->next is null only on the second call to AddNode. The first call to AddNode we go to the head = n; branch. On the second call, curr->next will be null and the while loop doesn't execute at all. But notice what happens after that, at the end of that second call. The curr->next = n; makes curr->next no longer null, appending n to this linked list. By the third call, curr->next is not null. The while loop iterates through the nodes with curr = curr->next until curr->next is null again (last node), then appends to that last node via curr->next = n;.

CodePudding user response:

It is checking it's current position and updating it every time until it reach end of a linked list Example:

[1->[address of 2 ] ,2->[address of 3 ],3->[address of 4 ],4->[address of 5 ],5->[NULL ]]
current = 1;

while loop start check the next of current if its not null update current value 
current =2
current =3
current=4
current=5
when it reach last element of linked list current next is now null it will stop.
outside of while loop add new element at the end of linked list 
  • Related