Search code examples
cpointerslinked-listsingly-linked-listfunction-definition

why insertion is not working in my link-list


I am learning linked list Here, I am trying to add node at the first so, I made a structure function to add but i dont know why its not working its only giving this output without adding

7 11 66 After insretion 7 11 66

and also please tell me is there any way to insert element on linked list.

// inserting element on first
#include<stdio.h>
#include<stdlib.h>

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

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


struct Node * insert_at_first(struct Node *head,int data){
    struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
    ptr->next=head;
    ptr->data=data;
    return ptr;
}

int main(){
    struct Node*head;
    struct Node*second;
    struct Node*third;
    head =(struct Node *) malloc(sizeof(struct Node));
    second =(struct Node *) malloc(sizeof(struct Node));
    third =(struct Node *) malloc(sizeof(struct Node));
   // linking first and secend node
    head ->data=7;
    head->next=second;
    // linking secend and third node
    second->data=11;
    second->next=third;
    // terminate the list at the third
    third->data=66;
    third->next=NULL;
    link_list_tranversal(head);

    insert_at_first(head,56);
    printf("After insretion\n ");
    link_list_tranversal(head);
    return 0;
}

Solution

  • After insert_at_first(head,56);, you've created a new node, but head is now pointing to the second node in the list and you have lost track of the newly created node. Simplest fix is to do: head = insert_at_first(head,56);. You can also pass &head and let the function update head.