When intially head is null,then in insertAtHead function why we cann’t directly allocate head->data=d and head->next=NULL .Why to create head=new node(d)?
Linked list insertion at beginning
hello @shubhangis248
head is NULL thats means head pointer is not pointing to any address
so if u will try to do head->data=d then it will give u segmentation fault.
but why segmentation fault as both data and d are of type int
segmentation occurs when we try to access invalid memory.
head=NULL, means head is not pointing to any address ,
and because head is not pointing to any address we r not allowed to peform any of these statement
head->next=NULL, or head->d=data;
so first assign some address to head using new operator and then u can perform these two operations
1 Like