Nicholas
Nicholas

Reputation: 13

Linked list insert end node in C

I'm currently learning about linked list in C and trying to write a function to insert a node at the end and then print all the data.

At first my function did not work (only 1 2 are printed)

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

void add_end(struct node *head, int a){
    struct node *current, *temp;
    current = head;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = a;
    temp->link = NULL;
    while(current != NULL){
        current = current->link;
    }
   current = temp;
};

int main()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->data = 1;
head->link = NULL;

struct node *current;
current = (struct node *)malloc(sizeof(struct node));
current->data = 2;
current->link = NULL;

head->link = current;

add_end(head, 3);

current = head;

while(current != NULL){
    printf("%d\n", current-> data);
    current = current->link;
    }

return 0;
}

After a while fixing it worked ( 1 2 3 are printed )

void add_end(struct node *head, int a){
    struct node *current, *temp;
    current = head;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = a;
    temp->link = NULL;
    while(current->link != NULL){
        current = current->link;
    }
   current->link = temp;
};

Can anyone tell me why the first one did not work pls. I thought they are the same because in the first version: current is the link of the last node which is the address of the next node (null) and in the second version: current->link is the link of the last node, which is the address of the next node (null) as well.

Upvotes: 0

Views: 491

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409482

Once current is NULL you have already passed the last node in the list, and current is a NULL pointer.

Assigning to it will not add the node to the list, it will just reassign current to no longer be a NULL pointer, but the last nodes link will not have been modified.

With the second function you find the actual last node in the list, and append the new node to the end.

Upvotes: 0

Related Questions