In this TED talk, Torvalds proposes a remove entry function without if conditions. I've tried to emulate in the code below, but it doesn't work if the entry to remove is the head of the list. 1.) Why does this fail to remove the head specifically? 2.) Doesn't this method generate a memory leak since we never free the entry?
/** a data structure representing a node **/
struct node {
int data;
struct node* next;
};
/** create a new node and return a pointer to it**/
struct node* new_Node(int data)
{
struct node* newP = malloc(sizeof(struct node));
newP-> data = data;
newP-> next = NULL;
return newP;
}
/** function to print out a list**/
void list_print(struct node* head)
{
printf("Begin List Print:\n");
struct node* tmp = malloc(sizeof(struct node));
tmp = head;
while(tmp != NULL ) {
printf("%d\n", tmp->data);
tmp = tmp->next;
}
printf("End List Print\n\n");
}
/** function to delete one node **/
void list_remove_entry(struct node* head, struct node* entry)
{
struct node** indirect = &head;
while((*indirect) != entry) {
indirect = &(*indirect)->next;
}
*indirect = (*indirect)->next;
}
/** the program entry point**/
int main()
{
struct node* head = new_Node(1);
struct node* n1 = new_Node(2);
struct node* n2 = new_Node(3);
head->next = n1;
n1->next = n2;
list_print(head);
list_remove_entry(head, head);
list_print(head);
return 0;
}