I have a linked List c file/head as an independent library i am using for a project. I dont yet have a add ordered method in the library. My problem is writing a compare function because i want to compare on different items for different projects. How do i create a compare function in my main for whatever project i am using then pass and use that function into the add_ordered method in my linked list library? I cant seem to find a workable solution to passing in the function and using it within my linked list.
here is a uncompiled version of my add_ordered and compareto methods (compare to method will be different for each file):
void ll_add_ordered(ll_node *head, void *d){
ll_node *cur;
ll_node *temp;
if(head->size == 0){
ll_add_first(head, d);
}else{
temp = (ll_node *)malloc(sizeof(ll_node));
temp->data = d;
for(cur = head->next; cur->data != NULL && compareTo(temp->data, cur->data); cur = cur->next)
;
temp->next = cur;
temp->prev = cur->prev;
cur->prev->next = temp;
cur->prev = temp;
head->size++;
}
}
int compareTo(proc *first, proc *second){
if(first->arrival < second->arrival)
return -1;
else if(first->arrival > second->arrival)
return 1;
else
return 0;
}
A simple solution would be to use a function pointer, and pass the pointer to the function.
I would recommend you declare an alias for the function signature as well, lest you get crazy after a while 🙂
I’m assuming
ll_node.datais of typevoid *. Thus your linked list requires two things:ll_add_ordered.The type alias for such a function pointer would be:
If you think this looks crazy, you’re totally right. It serves to make you
crazyhomicidial late nights when nothing works. Anyhow, what it really does is create a typedef for a function pointer and it calls the aliasll_comp_func.You would then alter your
ll_add_orderedinto the following form: