【问题标题】:Double linked list and void pointers [find method]双链表和空指针[查找方法]
【发布时间】:2013-12-10 09:33:42
【问题描述】:

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

 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) 我不知道如何实现这种类型的比较。

谢谢。

【问题讨论】:

  • 您是在比较指针还是它指向的(未知)类型?如果是后者,StoryTeller 的答案就是前进的方向。如果您只想比较指针,请使用== 与任何其他类型相同。

标签: c pointers void void-pointers doubly-linked-list


【解决方案1】:

要求用户提供一个回调(指向用户定义的函数的指针)来比较他的数据。以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;
}

【讨论】:

  • @SJuan76,这两个术语确实可以互换使用。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2014-11-29
    • 2011-03-19
    相关资源
    最近更新 更多