Search code examples
cwhile-looplinked-listnested-loops

Confusion about printing elements with double-while


Here are two linked lists 'list1' and 'list2'.

Where list1 and list2 have two datas : data1, data2.

They have nodes below : (data1, data2)

  • list1 : (1,1) - (2,2)
  • list2 : (3,3) - (4,4) - (5,5)

(bracket denotes each node)

while (list2 != NULL)
    {
        while (list1 != NULL)
        {
            printf("list1 contains : %d, %f\n", list1->data1, list1->data2);
            list1 = list1->NextNode;
        }

        printf("list2 contains : %d, %f\n", list2->data1, list2->data1);
        list2 = list2->NextNode;
    }

At First, I expected output as :

list1, list1, list2, list1, list1, list2, list1, list1, list2  

(I mean a printing order)

But I got :

list1, list1, list2, list2, list2.

So my question is:

  1. Why my expectation failed?

  2. How should I change my code to make code works like my expectation?

Thanks


Solution

  • After the first execution of the inner while loop (its first and single iteration)

    while (list2 != NULL)
        {
            while (list1 != NULL)
            {
                printf("list1 contains : %d, %f\n", list1->data1, list1->data2);
                list1 = list1->NextNode;
            }
    
            printf("list2 contains : %d, %f\n", list2->data1, list2->data1);
            list2 = list2->NextNode;
        }
    

    the pointer list1 becomes equal to NULL. Then after execution the code after the inner while loop the pointer list2 is also equal to NULL. So the both while loops have only one iterations.

    If you want to have the expected by you output like

    list1, list1, list2, list1, list1, list2, list1, list1, list2 
    

    then write for example. Let's assume that the type of an object of the list is Node

        while (list2 != NULL)
        {
            for ( Node *temp1 = list1; temp1 != NULL; temp1 = temp1->NextNode )
            {
                printf("list1 contains : %d, %f\n", temp1->data1, temp1->data2);
            }
    
            printf("list2 contains : %d, %f\n", list2->data1, list2->data1);
            list2 = list2->NextNode;
        }