我認爲你的計劃很好,使用指針authors
和main_characters
。由於您正在使用書籍,作者和主要角色的入侵鏈接列表,因此您可能會發現排除鏈接列表結構和操作很有幫助。
如果聲明是這樣的結構:
struct node
{
struct node *next;
struct node *previous;
};
typedef struct node node;
您可以將其嵌入到每個類型爲第一要素:
struct name
{
node linked_list;
char name_prefix[10];
char name_first[50];
char name_middle[50];
char name_last[50];
char name_suffix[5];
};
struct book
{
node linked_list;
name *authors;
name *main_characters;
/* variables for book */
char title[100]; /* the title of the book */
char publisher[100]; /* publisher */
//etc.
};
這使得你的類型convertible to the node
type。然後,您可以定義的node
類型方面鏈表操作:
void
node_add_node(node **head, node *object)
{
if (*head == NULL) {
*head = object;
}
else {
node *current, *previous;
for (current = *head; current != NULL; current = current->next) {
previous = current;
}
previous->next = object;
}
}
,然後定義類型安全的操作書的書籍和名稱的列表中添加書籍:
void
books_add_book(struct book **books, struct book *book)
{
node_add_node((node**)books, (node*)book);
}
void
book_add_author(struct book *book, struct name *author)
{
node_add_node((node**)&book->authors, (node*)author);
}
void
book_add_main_character(struct book *book, struct name *character)
{
node_add_node((node**)&book->main_characters, (node*)character);
}
然後,實現構造函數:
void node_init(node *node)
{
node->previous = NULL;
node->next = NULL;
}
struct book *
book_create(const char *title, const char *publisher)
{
struct book *b = malloc(sizeof(book));
if (b) {
node_init(&b->linked_list);
b->authors = NULL;
b->main_characters = NULL;
strcpy(b->title, title);
strcpy(b->publisher, publisher);
}
return b;
}
struct name *
name_create(const char *prefix, const char *first, const char *middle,
const char *last, const char *suffix)
{
name *n = malloc(sizeof(name));
if (n) {
node_init(&n->linked_list);
strcpy(n->name_prefix, prefix);
strcpy(n->name_first, first);
strcpy(n->name_middle, middle);
strcpy(n->name_last, last);
strcpy(n->name_suffix, suffix);
}
return n;
}
然後你就可以像這樣(注意創建的書:I增加Y的大小我們的name_prefix
到10):
struct book *books = NULL;
struct book *b = book_create("War and Peace", "Wordsworth");
struct name *n = name_create("Count", "Lev", "Nikolayevich", "Tolstoy", "");
book_add_author(b, n);
n = name_create("Count", "Pyotr", "Kirillovich", "Bezukhov", "");
book_add_main_character(b, n);
n = name_create("Countess", "Natalya", "Ilyinichna", "Rostova", "");
book_add_main_character(b, n);
books_add_book(&books, b);
'authors'和'main_characters'是列表的頭是不是他們?他們應該是指針。 –