Linked List: Insertion at beginning

Viewed 49

I am a beginner in data structure and I recently wrote a code to insert a new node at the beginning of a linked list using functions but when I run it the inserted node doesn't get printed, please help me verify the error in my code and correct it

#include <stdio.h>
#include <stdlib.h>

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

void
traversal(struct Node *ptr)
{
    while (ptr != NULL) {
        printf("%d\n", ptr->data);
        ptr = ptr->next;
    }
}

void
insert_first(struct Node *head, int data)
{
    struct Node *ptr = (struct Node *) malloc(sizeof(struct Node));

    ptr->data = data;
    ptr->next = head;
    head = ptr;
}

int
main()
{
    struct Node *head;
    struct Node *second;
    struct Node *third;
    struct Node *fourth;

    head = (struct Node *) malloc(sizeof(struct Node));
    second = (struct Node *) malloc(sizeof(struct Node));
    third = (struct Node *) malloc(sizeof(struct Node));
    fourth = (struct Node *) malloc(sizeof(struct Node));

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

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

    third->data = 30;
    third->next = fourth;

    fourth->data = 40;
    fourth->next = NULL;

    traversal(head);
    insert_first(head, 0);
    printf("\n");
    traversal(head);
    return 0;
}
1 Answers

insert_first() function parameter head is a local variable of insert_first() function. So, the statement head = ptr; will make changes in local variable only. These changes will not reflect in the pointer you have passed as first argument to insert_first() function.

As stated in one of the comments that you can return the updated value of head of list and assign that value to original head pointer of list.
Another way could be to pass the address of head pointer of list to insert_first() function (in case, if you want to keep the void as return type of insert_first() function).
For this, you have to changes the type of head parameter of insert_first() function from struct Node * to struct Node ** (double pointer) and pass the address of head (i.e. &head) to insert_first() function. Dereferencing head parameter of insert_first() function will give you the original pointer whose address you have passed and then you can make it point to some other address.

Implementation:

void
insert_first(struct Node **head, int data)
{
    struct Node *ptr = (struct Node *) malloc(sizeof(struct Node));

    ptr->data = data;
    ptr->next = *head;
    *head = ptr;
}

and call it like this

insert_first(&head, 0);
            ^^^ 

A suggestion:
Follow good programming practise - always check the malloc() return.

Related