图书管理系统链表c语言
时间: 2023-12-27 14:25:34 浏览: 89
以下是一个用C语言链表实现的图书管理系统的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义图书结构体
typedef struct Book {
char title[100];
char author[100];
int year;
struct Book* next;
} Book;
// 全局变量,指向链表的头节点
Book* head = NULL;
// 函数声明
void addBook();
void displayBooks();
void deleteBook(char* title);
void searchBook(char* title);
// 添加图书
void addBook() {
Book* newBook = (Book*)malloc(sizeof(Book));
printf("请输入书名:");
scanf("%s", newBook->title);
printf("请输入作者:");
scanf("%s", newBook->author);
printf("请输入出版年份:");
scanf("%d", &(newBook->year));
newBook->next = NULL;
if (head == NULL) {
head = newBook;
} else {
Book* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newBook;
}
printf("图书添加成功!\n");
}
// 显示所有图书
void displayBooks() {
if (head == NULL) {
printf("图书馆为空!\n");
return;
}
Book* current = head;
printf("图书列表:\n");
while (current != NULL) {
printf("书名:%s,作者:%s,出版年份:%d\n", current->title, current->author, current->year);
current = current->next;
}
}
// 删除图书
void deleteBook(char* title) {
if (head == NULL) {
printf("图书馆为空!\n");
return;
}
Book* current = head;
Book* previous = NULL;
while (current != NULL) {
if (strcmp(current->title, title) == 0) {
if (previous == NULL) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
printf("图书删除成功!\n");
return;
}
previous = current;
current = current->next;
}
printf("未找到该图书!\n");
}
// 查找图书
void searchBook(char* title) {
if (head == NULL) {
printf("图书馆为空!\n");
return;
}
Book* current = head;
while (current != NULL) {
if (strcmp(current->title, title) == 0) {
printf("书名:%s,作者:%s,出版年份:%d\n", current->title, current->author, current->year);
return;
}
current = current->next;
}
printf("未找到该图书!\n");
}
int main() {
int choice;
char title[100];
while (1) {
printf("\n图书管理系统\n");
printf("1. 添加图书\n");
printf("2. 显示所有图书\n");
printf("3. 删除图书\n");
printf("4. 查找图书\n");
printf("5. 退出\n");
printf("请输入您的选择:");
scanf("%d", &choice);
switch (choice) {
case 1:
addBook();
break;
case 2:
displayBooks();
break;
case 3:
printf("请输入要删除的图书的书名:");
scanf("%s", title);
deleteBook(title);
break;
case 4:
printf("请输入要查找的图书的书名:");
scanf("%s", title);
searchBook(title);
break;
case 5:
printf("感谢使用图书管理系统!\n");
exit(0);
default:
printf("无效的选择!\n");
}
}
return 0;
}
```
阅读全文