簡體   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