用c语言代码写基于线性表的图书信息管理的链式存储表示
时间: 2024-11-18 17:15:45 浏览: 26
在C语言中,我们可以使用链表数据结构来实现图书信息管理。链表是一种动态数据结构,每个节点包含数据域和指针域,用于链接到下一个节点。下面是一个简单的例子,展示了如何创建一个链表节点结构以及用于图书信息的基本操作,如添加、删除和查找书籍。
首先,我们定义一个链表节点(BookNode)结构:
```c
typedef struct {
char title[50]; // 图书标题
char author[50]; // 作者名
int year; // 出版年份
struct BookNode* next; // 指向下一个节点的指针
} BookNode;
```
接下来,我们创建链表相关的函数:
1. 初始化链表:
```c
void createEmptyList(BookNode** list) {
*list = NULL;
}
```
2. 添加新书:
```c
void addBook(BookNode** head, char* title, char* author, int year) {
BookNode* newNode = (BookNode*)malloc(sizeof(BookNode));
if (newNode != NULL) {
strcpy(newNode->title, title);
strcpy(newNode->author, author);
newNode->year = year;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
BookNode* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
}
```
3. 删除书籍:
```c
void deleteBook(BookNode** head, char* title) {
if (*head == NULL) return;
BookNode* current = *head;
if (strcmp(current->title, title) == 0) {
BookNode* temp = *head;
*head = temp->next;
free(temp);
return;
}
while (current->next != NULL && strcmp(current->next->title, title) != 0) {
current = current->next;
}
if (current->next != NULL) {
BookNode* temp = current->next;
current->next = temp->next;
free(temp);
}
}
```
4. 查找书籍:
```c
BookNode* findBook(BookNode* head, char* title) {
BookNode* current = head;
while (current != NULL) {
if (strcmp(current->title, title) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
```
阅读全文