双链表,空指针[find方法] [英] Double linked list and void pointers [find method]
本文介绍了双链表,空指针[find方法]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了空指针这个双向链表
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);
,其中** l_ptr是指针列表以搜索和埃尔是要搜索的元素。
因为我想比较两个无效*(无效* E1和无效*数据),我不知道如何实现这种类型的比较。
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.
感谢。
推荐答案
要求用户提供一个回调(指针的函数定义的用户),比较他的数据。看看 的qsort
例如
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;
}
这篇关于双链表,空指针[find方法]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文