用c语言编写链式结构图书信息表,包含输入,查找,删除功能
时间: 2024-10-21 16:10:43 浏览: 42
在C语言中,我们可以使用链表数据结构来创建一个简单的图书信息表。这里我会给出一个基础的示例,包括如何创建节点、插入书籍信息、查找特定书籍以及删除一本书。首先,我们需要定义一个结构体`BookInfo`表示每本书的基本信息,如书名、作者等;然后定义一个`Node`结构体用于存储`BookInfo`并链接到下一个节点。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct BookInfo {
char title[50];
char author[50];
struct Node* next;
} BookInfo;
typedef struct Node {
BookInfo info;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(BookInfo book) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->info = book;
newNode->next = NULL;
return newNode;
}
// 插入书籍
void insertBook(BookInfo book, Node** head) {
Node* newNode = createNode(book);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找书籍
BookInfo* searchBook(char* title, Node* head) {
Node* current = head;
while (current != NULL) {
if (strcmp(current->info.title, title) == 0) {
return ¤t->info;
}
current = current->next;
}
return NULL; // 如果未找到,则返回NULL
}
// 删除书籍
void deleteBook(char* title, Node** head) {
if (*head == NULL) return;
if ((*head)->info.title == title) { // 如果头节点就是目标
Node* temp = *head;
*head = (*head)->next;
free(temp); // 释放头节点
} else {
Node* prev = *head;
Node* current = *head->next;
while (current != NULL && strcmp(current->info.title, title) != 0) {
prev = current;
current = current->next;
}
if (current != NULL) { // 找到了目标节点
prev->next = current->next;
free(current); // 释放当前节点
}
}
}
int main() {
Node* head = NULL;
// 示例操作
BookInfo book1 = {"图书A", "作者A", NULL};
insertBook(book1, &head);
// 查找并打印
BookInfo* found = searchBook("图书A", head);
if (found) {
printf("找到书籍:%s\n", found->title);
}
// 删除
deleteBook("图书A", &head);
return 0;
}
```
阅读全文