Alcon Blue
Alcon Blue

Reputation: 13

How to insert Node at end of Linked List?

I am a beginner in Data Structures and I want to know how insert node at the end of a linked list. With the following code I am able to insert node in the beginning and in the any other position except at the end of the linked list. But when it comes to inserting a node at the end I am unable to do so.

void Insert(NODE *head,int n,int pos)
{
     NODE  *temp, *newnode;
     int i;
     for(temp = head, i = 1; ( temp != NULL ) && ( i <= pos-1 ); i++)
     {

         if(temp->next==NULL)
         {
             printf("\nPosition is out of range.\n\n");
         }
         

     }
          newnode = (NODE*)malloc(sizeof(NODE));
          newnode->info = n;
          newnode->next = temp->next;
          temp->next = newnode;
}

When I go for inserting node at the end it gives following output " Position out of range." I sort of understand why it gives that output, but I am not able to find how should I change my code. Thank You.

Upvotes: 0

Views: 216

Answers (1)

Ptit Xav
Ptit Xav

Reputation: 3219

Comment on your code :

for(temp = head, i = 1; ( temp != NULL ) && ( i <= pos-1 ); i++)
{

     if(temp->next==NULL) // Adding at the end means that you add when
                          // temp-> next is NULL
     {
         printf("\nPosition is out of range.\n\n");
     }
     

 }

For example, if you a 1 element in the list and insert at position 2, you will have (i <= pos-1) true and (temp->next==NULL) true.

Upvotes: 0

Related Questions