Double linked list and void pointers [find method]

筅森魡賤 提交于 2019-12-12 01:06:34

问题


i wrote this double linked list with void pointers

 typedef struct list_el
 { 
    void *data;            
    struct list_el *prev;  
    struct list_el *next; 

 } list_el;


typedef struct linked_list
{
   int n_el;            /*number of elements*/      
   list_el * head;      /*pointer to the head*/ 
   list_el * tail;      /*pointer to the head*/ 

 } linked_list;

and i wrote those functions to handle with it.

/*for list_el allocation*/
list_el * new_el ( void )
{
    return (list_el *) malloc(sizeof(list_el));
}

/*list initialization*/
void init_list(linked_list **l_ptr)
{
    (*l_ptr) = (linked_list * )malloc(sizeof(linked_list)); 
    (*l_ptr)->n_el = 0;
    (*l_ptr)->head = NULL;
    (*l_ptr)->tail = NULL;
}

/*head insertion*/
void append(void *data , linked_list **l_ptr)
{
    list_el *nv;
    nv = new_el();

    nv->data = data;

    if((*l_ptr)->n_el == 0 )
    {
        nv->next = nv->prev = NULL;
        (*l_ptr)->head = (*l_ptr)->tail = nv;
        (*l_ptr)->n_el += 1;
    }
    else
    {
       nv->next = (*l_ptr)->head;
       (*l_ptr)->head->prev = nv;
       (*l_ptr)->head = nv;
       (*l_ptr)->n_el += 1;
    }
}

I'm trying to write a find function in this way.

void * find(void * el , linked_list ** l_ptr);

where **l_ptr is the pointer to the list to search in and el is the element to search. since I'm trying to compare two void * (void * el and void *data) I do not know how to implement a comparison of this type.

Thanks.


回答1:


Ask the user to provide a callback (a pointer to a function the user defined) for comparing his data. Look at qsort for example.

typedef int (*linked_list_compare)(void*, void*);

typedef struct linked_list
{
   int n_el;            /*number of elements*/      
   list_el * head;      /*pointer to the head*/ 
   list_el * tail;      /*pointer to the head*/ 

   linked_list_compare data_compare_func;

} linked_list;

void init_list(linked_list **l_ptr, linked_list_compare compare_func)
{
    if (!l_ptr || !compare_func)
      return; /* You should do error checking and error reporting */
    (*l_ptr) = (linked_list * )malloc(sizeof(linked_list)); 
    (*l_ptr)->n_el = 0;
    (*l_ptr)->head = NULL;
    (*l_ptr)->tail = NULL;
    (*l_ptr)->data_compare_func = compare_func;
}



回答2:


Actually I was going to say that since a void pointer is pointing to an address which holds data but the data type hence size is unknown, you have to use casting in order to do it properly by value. I think that the only good way to do it is exactly the way StoryTeller proposes, you give the user (or maybe in this case you) the possibility to compare the data the way he wants and return -1, 0, or 1.



来源:https://stackoverflow.com/questions/20196787/double-linked-list-and-void-pointers-find-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!