繁体   English   中英

双链表和空指针[查找方法]

[英]Double linked list and void pointers [find method]

我用空指针写了这个双链表

 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;

我写了那些函数来处理它。

/*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;
    }
}

我正在尝试以这种方式编写查找功能。

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

其中** l_ptr是指向要搜索的列表的指针,而el是要搜索的元素。 因为我要比较两个void *(void * el和void * data),所以我不知道如何实现此类型的比较。

谢谢。

要求用户提供一个回调(指向用户定义的函数的指针)以比较其数据。 qsort为例。

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;
}

实际上,我要说的是,由于void指针指向的是保存数据的地址,但是数据类型因而大小是未知的,因此必须使用强制转换才能按值正确进行处理。 我认为,做到这一点的唯一好方法就是StoryTeller提出的方法,即让用户(或者在这种情况下,您)可以按自己想要的方式比较数据并返回-1、0或1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM