2013-11-25 29 views
0

我寫了這雙鏈表與空指針雙鏈表和空指針[找到方法]

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)我不知道如何實現這種類型的比較。

謝謝。

+0

你想比較指針,還是指向它的(未知)類型?如果是後者,StoryTeller的回答是前進的方向。如果您只想比較指針,請使用與其他類型相同的「==」。 – Useless

回答

2

要求用戶提供一個回調函數(一個指向用戶定義的函數的指針)來比較他的數據。例如,看看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; 
} 
+0

回調=函數指針 – SJuan76

+0

@ SJuan76,實際上兩個術語可以互換使用。 – StoryTeller

2

其實我要說的是,由於一個空指針指向哪個保存數據,但一個地址中的數據類型,因此大小是未知的,你必須按順序通過值做正確使用鑄造。我認爲這樣做的唯一好方法就是StoryTeller提出的方式,您可以讓用戶(或者在這種情況下)給出他想要的方式比較數據並返回-1,0或1的可能性。