2012-10-11 12 views
0

有沒有辦法爲不同的結構編寫單個函數(addnode)?我有這樣的場景:函數addnode爲不同的鏈表結構

typedef struct linkedlist_a *ptr_a; 
typedef struct linkedlist_a 
{ 
    /* content */ 
    ptr_a next; 
} listA; 

typedef struct linkedlist_b *ptr_b; 
typedef struct linkedlist_b 
{ 
    /* content */ 
    ptr_b next; 
} listB; 

listA *listA_addnode(listA *head, listA *node) 
{ 
    listA *temp = head; 
    if(temp == NULL) 
    { 
     temp = node; 
    } 
    else if(temp -> next == NULL) 
    { 
     temp -> next = node; 
    } 
    else 
    { 
     while(temp -> next) temp = temp -> next; 
     temp -> next = node;   
    } 

    return head; 
} 


listB *listB_addnode(listB *head, listB *node) 
{ 
    listB *temp = head; 
    if(temp == NULL) 
    { 
     temp = node; 
    } 
    else if(temp -> next == NULL) 
    { 
     temp -> next = node; 
    } 
    else 
    { 
     while(temp -> next) temp = temp -> next; 
     temp -> next = node;   
    } 

    return head; 
} 

如果有兩大系結構是好的,我寫兩個功能,但萬一我有超過2個,我該怎麼辦?

+0

你聲明瞭兩個不同的鏈表來保存不同類型的? – Ifthikhan

+0

如果您在空列表上調用addnode()函數,它將不起作用 - 您需要將頭指向新分配的節點 – Raj

回答

1

而不是有代表鏈接列表不同的struct可能的解決方案將是有單個鏈接列表struct具有void*成員的數據。這將允許一個add_node()函數具有稍微不同的簽名。

例如:

struct linked_node 
{ 
    void* data; 
    struct linked_node* next; 
}; 

void add_node(struct linked_node** a_head, void* a_data) 
{ 
    struct linked_node* new_node = malloc(sizeof(*new_node)); 
    new_node->data = a_data; 
    new_node->next = 0; 
    if (!*a_head) 
    { 
     *a_head = new_node; 
    } 
    else 
    { 
     /* ... */ 
    } 
} 

有這種方法,即正確解釋data成員的危險。但是,謹慎地使用這種方法可以滿足您的要求。

實施例使用(檢查省略錯誤):

struct data_x { int i; char c; }; 
struct data_y { char* s; }; 

struct linked_node* list_x = 0; 
struct data_x* dx = malloc(sizeof(*dx)); 
dx->i = 4; 
dx->c = 'a'; 

add_node(&list_x, dx); 

if (list_x) 
{ 
    struct data_x* x = list_x->data; 
    printf("x.i=%d x.c=%c\n", x->i, x->c); 
} 

struct linked_node* list_y = 0; 
struct data_y* dy = malloc(sizeof(*dy)); 
dy->s = "hello"; 

add_node(&list_y, dy); 

if (list_y) 
{ 
    struct data_y* y = list_y->data; 
    printf("y.s=%s\n", y->s); 
} 

查看在線演示http://ideone.com/iZO8h

+0

「data」可以是一個包裝結構,它嵌入了值和類型信息這將允許您在運行時推斷和投射。 – Ifthikhan

+0

非常感謝你,那就是我一直在尋找的東西。 – wsknorth

0

只有這樣做的方法是使用一個宏,假設您的鏈接元素被稱爲相同(next存在於您希望通過的所有類型中)。

GNU風格進取代碼:-std=gnu98以上

#define addnode(head, node) ({\ 
    typeof(head) _head = (head);\ 
    typeof(node) _node = (node);\ 
    if(_head == NULL)\ 
    {\ 
     _head = _node;\ 
    }\ 
    else\ 
    {\ 
     while(_head -> next) _head = _head -> next;\ 
     _head -> next = _node;  \ 
    }\ 
    \ 
    _head;\ 
}) 

這是非常糟糕的編程風格,雖然