Insert at Head - Linked List

In the following function the return type of insertAtHead is void but we are changing head (which is not global) then why we not returning head value? And return tye should be node *

void insertAtHead(node* head, int data){
node *temp = new node(data);
temp->next = head;
head = temp;
}

int main(){
node* head = NULL;
return 0;
}

this function won’t work.
to change the value of the head node
you need to pass the value by reference or return the new head pointer.

void insertAtHead(node* &head, int data)
node* insertAtHead(node* head, int data)

are the function prototypes that can be used for this.

2 Likes

your problem solution is very well explained in the same video by prateek bhaiya where you got this problem watch out the complete video of linked list insertion at head

1 Like

You are right. Either we should return it or we should accept it by reference or use double star.

void insertAtHead(node*&head,int data){
head = ptr to some new address;
}

void insertAtHead(node**head,int data){
*head = ptr to some new address;
}

That will serve the purpose.

1 Like