0

有没有办法为不同的结构编写单个函数( 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 个,我该怎么办?

4

2 回答 2

1

一个可能的解决方案是使用具有数据成员的struct单个链表,而不是使用不同的 s 来表示链表。这将允许具有稍微不同签名的单个函数。structvoid*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

于 2012-10-11T08:16:17.243 回答
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;\
})

虽然这是一种非常糟糕的编程风格

于 2012-10-11T08:22:50.703 回答