请用C语言建立图书信息的线性表结构(链表),并在此基础上完成增、删、改、查等基本操作,代码以文档方式上交,同时需要运行结果
时间: 2024-09-22 20:04:24 浏览: 40
在C语言中,我们可以使用结构体和链表数据结构来创建一个简单的图书信息管理。首先,我们定义一个`Book`结构体存储图书的基本信息,比如书名、作者和ISBN:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义图书结构体
typedef struct Book {
char title[100];
char author[100];
char isbn[13]; // 假设ISBN是13位数字
} Book;
// 创建一个新的图书节点
Book* create_book(char* title, char* author, char* isbn) {
Book* new_book = (Book*) malloc(sizeof(Book));
if (new_book) {
strcpy(new_book->title, title);
strcpy(new_book->author, author);
strcpy(new_book->isbn, isbn);
return new_book;
}
printf("内存分配失败\n");
return NULL;
}
// 线性表结构,包含头指针和链表长度
typedef struct {
Book* head;
int size;
} Library;
// 初始化一个空图书馆
Library* init_library() {
Library* library = (Library*) malloc(sizeof(Library));
library->head = NULL;
library->size = 0;
return library;
}
// 添加图书到列表末尾
void add_book(Library* library, char* title, char* author, char* isbn) {
Book* new_book = create_book(title, author, isbn);
if (new_book) {
new_book->next = NULL;
if (!library->head) {
library->head = new_book;
} else {
Book* current = library->head;
while (current->next) {
current = current->next;
}
current->next = new_book;
}
library->size++;
}
}
// 删除指定图书
void delete_book(Library* library, char* isbn) {
if (!library || !library->head) {
return;
}
Book* current = library->head;
Book* previous = NULL;
while (current && strcmp(current->isbn, isbn)) {
previous = current;
current = current->next;
}
if (current == NULL) {
printf("找不到该图书\n");
return;
}
if (previous) {
previous->next = current->next;
} else {
library->head = current->next;
}
free(current);
library->size--;
}
// 修改图书信息
void update_book(Library* library, char* old_isbn, char* new_title, char* new_author) {
Book* current = library->head;
while (current) {
if (strcmp(current->isbn, old_isbn) == 0) {
strcpy(current->title, new_title);
strcpy(current->author, new_author);
printf("图书 %s 的信息已更新为:%s - %s\n", current->isbn, current->title, current->author);
break;
}
current = current->next;
}
}
// 搜索图书
void search_book(Library* library, char* isbn) {
Book* current = library->head;
while (current) {
if (strcmp(current->isbn, isbn) == 0) {
printf("找到图书:标题 - %s,作者 - %s\n", current->title, current->author);
break;
}
current = current->next;
}
if (!current) {
printf("未找到图书 %s\n", isbn);
}
}
int main() {
Library* library = init_library();
// 示例操作
add_book(library, "红楼梦", "曹雪芹", "9787532746655");
search_book(library, "9787532746655"); // 查询示例
update_book(library, "9787532746655", "石头记", "曹雪芹修订版");
delete_book(library, "9787532746655"); // 删除示例
free(library);
return 0;
}
```
阅读全文