Home > Blockchain >  Difference between temp!=NULL and temp->next!=NULL?
Difference between temp!=NULL and temp->next!=NULL?

Time:09-13

//i was creating a linked list and tranverse it

but in the while condition in the function , i was confused about wheater to put temp!=NULL or temp!=NULL. both showed different output. please help out. why they are different . . . . . .

#include <stdio.h>
#include <stdlib.h>
 
struct brick
{
    int data;
    struct  brick * next; // self refrencing pointer
};

void printval(struct brick * temp);

void printval(struct brick * temp)
{ 
    int i = 0;
    while (temp != NULL)
    {    
        printf("elements at index %d=%d \n", i, temp->data);
        temp = temp->next;
        i  ;
    }
}

int main()
{
    struct brick *first, *second, *third;
    first = (struct brick *)malloc(sizeof(struct brick));
    second = (struct brick *)malloc(sizeof(struct brick));
    third = (struct brick *)malloc(sizeof(struct brick));

    first->data = 1;
    first->next = second;
 
    second->data = 2;
    second->next = third;
 
    third->data = 3;
    third->next = NULL;
 
    printval(first);
    
    return 0;
} 

CodePudding user response:

I always tend to think of what I have stored in temp AFTER the loop to help me decide the conditional I want to use. For example:

i) while(temp!=NULL) { }
The condition that breaks the loop is when temp == NULL. Hence immediately after the loop your temp points to the NULL.

ii) while(temp->next!=NULL) {}
The condition that gets you out of the while loop is when temp->next==NULL, i.e it exits when temp is pointing to the last node in the linked list. Hence, temp would point to the last element once I'm out of the while loop.

So if you want the loop to run for the whole list including the last element in the linked list, you use (temp!=NULL) but if you want the loop to run till the second last element, you would generally use (temp->next=NULL)

CodePudding user response:

If you check if temp != NULL your loop will terminate when you get to the end of the list. If you check for temp->next != NULL your loop will stop at the next to last element in the list.

It may help to visualize your list.

 -------------------- 
| First              |
| int data           |
| struct brick *next --\
 --------------------  |
      /----------------/
      |
      v
      --------------------      
     | Second             |
     | int data           |
     | struct brick *next --\
      --------------------  |     
           /----------------/
           |
           v
           --------------------      
          | Second             |
          | int data           |    
          | struct brick *next --\  
           --------------------  |
                                 |
                                 v
                                 ------ 
                                | NULL |
                                 ------ 
  • Related