用c语言链表制作图书信息管理系统
时间: 2024-11-09 22:22:24 浏览: 19
C语言链表实现图书管理系统
在C语言中,创建一个图书信息管理系统的链表通常是用于存储书籍的数据结构,例如书名、作者、出版社等。以下是一个简单的示例,展示如何用链表数据结构来设计这个系统:
首先,我们需要定义一个`Book`节点结构,包含书籍的基本属性:
```c
typedef struct Book {
char title[50];
char author[50];
char publisher[50];
int id;
struct Book* next; // 指向下一个节点的指针
} BookNode;
```
接着,我们可以定义一些操作函数:
1. **初始化**:创建一个新的链表
```c
BookNode* createList() {
BookNode* head = NULL;
return head;
}
```
2. **添加书籍**:在链表尾部插入新书
```c
void addBook(BookNode** head, char title[], char author[], char publisher[], int id) {
BookNode* newNode = (BookNode*)malloc(sizeof(BookNode));
if (newNode != NULL) {
strncpy(newNode->title, title, sizeof(newNode->title) - 1);
strncpy(newNode->author, author, sizeof(newNode->author) - 1);
strncpy(newNode->publisher, publisher, sizeof(newNode->publisher) - 1);
newNode->id = id;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
BookNode* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
}
```
3. **搜索书籍**:通过ID查找特定的书
```c
BookNode* findBookById(BookNode* head, int id) {
BookNode* current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL;
}
```
4. **显示所有书籍**:遍历链表打印信息
```c
void displayBooks(BookNode* head) {
if (head == NULL) {
printf("No books in the list.\n");
} else {
BookNode* current = head;
while (current != NULL) {
printf("Title: %s\nAuthor: %s\nPublisher: %s\nID: %d\n",
current->title, current->author, current->publisher, current->id);
current = current->next;
}
}
}
```
阅读全文