Search code examples
cdata-structureslinked-listinsertion

Inserting a node at the end of a linked list


#include <stdio.h>
#include <conio.h>

struct node
{
    int data;
    struct node* next;
};

int main()
{
    struct node* head = NULL;
    struct node* second = NULL;
    struct node* third = NULL;

    head = (struct node*)malloc(sizeof(struct node));
    second = (struct node*)malloc(sizeof(struct node));
    third = (struct node*)malloc(sizeof(struct node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    struct node* new1;
    struct node* temp1;

    temp1 = head;

    while(temp1->next != NULL)
    {
        temp1 = temp1->next;
    }

    new1 = (struct node*)malloc(sizeof(struct node));

    temp1->next = new1;
    new1->data = 5;
    new1->next = NULL;

    while(temp1 != NULL)
    {
        printf("%d ",temp1->data);
        temp1 = temp1->next;
    }

    return 0;
}

This is the program for inserting a node at the end of linked list. The expected output is = 1 2 3 5, 5 is the new node's value here. But the current output is = 3 5. I don't know where am I wrong. Any answer will be appreciated.


Solution

  • while(temp1->next != NULL)
     {
        temp1 = temp1->next;
     }
    

    After this loop your temp1 is at the end of the list and you are adding a node at the end of the list.

    Now you are trying to print from temp1 obviously you will get only 2 nodes new one and the one before it. If you want the whole list print from head. Just before printing after adding your new node. Point temp1 to head.

    temp1 = head;
    while(temp1 != NULL)
    {
        printf("%d ",temp1->data);
        temp1 = temp1->next;
    }