I wrote the function below to insert a value in order into the linked list, using a cmp function defined by the user. So i tested this out, I wrote my own cmp function for integers, and put in the values 9 and 1. The output was 9 and 1 (it did not insert into the linked list in order). After debugging this function for a while, I figured that if(prev == NULL) is never true, hence my program is breaking, is there anything I am doing wrong here???, we can compare to NULL right?
list_t *insert_in_order(list_t *list, void *value, int (*cmp)(void*,void*)) {
node_t *new_node, *curr, *prev;
new_node = (node_t *)malloc(sizeof(*new_node));
assert(new_node != NULL && list != NULL);
new_node->data = value;
/*Special case when the list is empty*/
if(list->head == NULL) {
new_node->next = NULL;
list->head = list->foot = new_node;
}
/*List is obviously not empty*/
else {
curr = list->head;
prev = NULL;
/*Traverse the list*/
while(curr) {
/*I am basically going to break the loop when I find the right position*/
/*to insert the node (after this node called prev)*/
if(cmp(curr->data, value) > 0) {
break;
}
prev = curr;
curr = curr->next;
}
/*So now I know the node will go after the prev (defined above) node.*/
/*Special case if this is the 0th position in the linked list i.e prev is null*/
if(prev == NULL) {
/*After doing some printfs here I see that prev is never null, anything*/
/*wrong here???????????*/
printf("prev is null\n");
new_node->next = list->head;
list->head = new_node;
}
else {
printf("prev is not null\n");
new_node->next = prev->next;
prev->next = new_node;
}
}
return list;
}