Kyouma45
Kyouma45

Reputation: 1

Insert at the end in a linked list in c

For some reason my code is not running insert function. I want to add a node at the end, but because of some error, my second half of the code is not executed which is strange cause compiler doesn't throw any error.

//Inserting at the end
#include <stdio.h>
#include <stdlib.h>

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

void display(struct Node * head)
{
    int i=1;
    while(head!=NULL){
    printf("Element %d: %d\n",i,head->data);
    i++;
    head=head->next;
    }
}

void insert(struct Node* head,int p)
{
    struct Node *last = (struct Node *)malloc(sizeof(struct Node));
    last->next=NULL;
    last->data=p;
    while (head!=NULL)
    {       
        head=head->next;
    }
    head->next=last;
    printf("%d\t%d",head->data,last->data);  //to check insert function
}

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

    first->data = 7;
    first->next = second;

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

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

    display(first);
    insert(first,24);
    display(first);

    return 0;
}

It is not even giving me any garbage value.

Upvotes: 0

Views: 105

Answers (1)

paddy
paddy

Reputation: 63471

When you scan to the end of the list, you're doing this:

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

The problem is that when this loop finishes, head is now NULL and then you attempt:

head->next = last;  //<-- BOOM!

Change the loop to this:

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

Now, your loop will finish when the object pointed to by head has no next pointer.

This does assume that you never pass NULL to the insert function, but that should be okay because it appears to be a precondition anyway. So just make sure you never do that! Even if you wanted to allow insertion into an empty list, there's currently no way for you to return a new list head.

Upvotes: 2

Related Questions