2.2) Return head pointer: We can write deleteFirst() in such a way that it returns the modified head pointer. Whoever is using this function, have to use the returned value to update the head node.
struct node *deleteFirst( struct node *head) { if (head != NULL) { // store the old value of head pointer struct node *temp = head; // Change head pointer to point to next node head = head->next; // delete memory allocated for the previous head node free (temp); } return head; } |
2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify local variable of one function inside another function, pass pointer to that variable. So we can pass pointer to the head pointer to modify the head pointer in our deleteFirst() function.
void deleteFirst( struct node **head_ref) { if (*head_ref != NULL) { // store the old value of pointer to head pointer struct node *temp = *head_ref; // Change head pointer to point to next node *head_ref = (*head_ref)->next; // delete memory allocated for the previous head node free (temp); } }
Read full article from How to write C functions that modify head pointer of a Linked List? | GeeksforGeeks
|