创建一个包含n个图书的链表
时间: 2023-08-20 09:37:06 浏览: 41
好的,下面是一个简单的示例代码来创建一个包含n个图书的链表:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义一个图书结构体
struct book {
char title[50];
char author[50];
int pages;
int year;
};
// 定义一个链表节点结构体
struct node {
struct book data;
struct node *next;
};
// 创建一个新的节点
struct node *create_node(struct book data) {
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// 在链表末尾插入一个新节点
void insert_node(struct node **head_ref, struct book data) {
struct node *new_node = create_node(data);
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
struct node *last_node = *head_ref;
while (last_node->next != NULL) {
last_node = last_node->next;
}
last_node->next = new_node;
}
// 创建一个包含n个图书的链表
struct node *create_book_list(int n) {
struct node *head = NULL;
struct book new_book;
for (int i = 0; i < n; i++) {
printf("Enter the details of book %d:\n", i+1);
printf("Title: ");
scanf("%s", new_book.title);
printf("Author: ");
scanf("%s", new_book.author);
printf("Pages: ");
scanf("%d", &new_book.pages);
printf("Year: ");
scanf("%d", &new_book.year);
insert_node(&head, new_book);
}
return head;
}
// 打印链表中的所有节点
void print_list(struct node *head) {
struct node *current_node = head;
while (current_node != NULL) {
printf("%s, written by %s, %d pages, published in %d\n", current_node->data.title, current_node->data.author, current_node->data.pages, current_node->data.year);
current_node = current_node->next;
}
}
int main() {
int n;
printf("Enter the number of books: ");
scanf("%d", &n);
struct node *book_list = create_book_list(n);
printf("\nBook list:\n");
print_list(book_list);
return 0;
}
```
这个程序会要求你输入n个图书的信息,然后创建一个包含n个图书的链表,并将链表打印出来。你可以根据自己的需要修改图书结构体的成员或者增加新的成员。