void addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -> data = n; temp -> link = head; head = temp; }
The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list. Generally the correct versions are like,
void addNewNode (struct node **head, int n); void addNewNode (struct node * &head, int n);
I worked out another but simple function for the purpose which worked fine.
struct node* addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -> data = n; temp -> link = head; return temp; }
But I haven’t seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.
The flaw is that you’re relying on the caller to perform the last step of updating the head pointer to the list.
If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you’ll have leaked the memory for a node).