【发布时间】:2018-08-14 04:38:02
【问题描述】:
我有两种或多种不同类型的结构,它们使用它们自己类型的节点的链表,我注意到检索、删除、插入和检查节点是否存在的代码在所有结构中都是相同的当代码被重复时。有没有更好的办法?
猫屋
typedef struct Cat Cat;
struct Cat {};
typedef struct CatNode CatNode;
struct CatNode {
char *name;
Cat *cat;
CatNode *next;
};
typedef struct CatHouse CatHouse;
struct CatHouse {
CatNode *cats;
Proxy *(*getCat)(const CatHouse *self, const char *name);
bool (*hasCat)(const CatHouse *self, const char *name);
Proxy *(*remove)(CatHouse *self, const char *name);
};
狗屋
typedef struct Dog Dog;
struct Dog {};
typedef struct DogNode DogNode;
struct DogNode {
char *name;
Dog *dog;
DogNode *next;
};
typedef struct DogHouse DogHouse;
struct DogHouse {
DogNode *dogs;
Dog *(*getDog)(const DogHouse *self, const char *name);
bool (*hasDog)(const DogHouse *self, const char *name);
Dog *(*remove)(DogHouse *self, const char *name);
};
这是在两个实体中重复的部分实现。
如果重复是如何完成的,我很好,我也想知道如何在商业项目中处理链表,因为它们有多个实体结构,每个都有自己的链表,而且可能不止一个?
static bool hasCat(const Cat *self, const char *name) {
CatNode *cursor = self->cats;
while (cursor != NULL && strcmp(cursor->name, name) != 0)
cursor = cursor->next;
return cursor != NULL;
}
static bool hasDog(const Dog *self, const char *name) {
DogNode *cursor = self->dogs;
while (cursor != NULL && strcmp(cursor->name, name) != 0)
cursor = cursor->next;
return cursor != NULL;
}
除了类型不同之外,其余的功能也类似地重复。
【问题讨论】:
-
一种方法是使用大量宏:)
标签: c linked-list