c语言中用链表实现图书管理系统
时间: 2023-05-29 07:07:11 浏览: 196
下面是一个简单的图书管理系统的链表实现,包括添加书籍、删除书籍、查找书籍和显示所有书籍的功能。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct book {
char name[50];
char author[50];
int ISBN;
struct book *next;
} Book;
Book *head = NULL;
void add_book() {
Book *new_book = (Book*)malloc(sizeof(Book));
printf("Enter book name: ");
scanf("%s", new_book->name);
printf("Enter author name: ");
scanf("%s", new_book->author);
printf("Enter ISBN: ");
scanf("%d", &new_book->ISBN);
new_book->next = NULL;
if (head == NULL) {
head = new_book;
} else {
Book *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_book;
}
printf("Book added successfully!\n");
}
void delete_book() {
int ISBN;
printf("Enter ISBN of book to delete: ");
scanf("%d", &ISBN);
if (head == NULL) {
printf("Library is empty!\n");
return;
} else if (head->ISBN == ISBN) {
Book *temp = head;
head = head->next;
free(temp);
printf("Book deleted successfully!\n");
return;
} else {
Book *temp = head;
while (temp->next != NULL && temp->next->ISBN != ISBN) {
temp = temp->next;
}
if (temp->next == NULL) {
printf("Book not found!\n");
return;
} else {
Book *to_delete = temp->next;
temp->next = to_delete->next;
free(to_delete);
printf("Book deleted successfully!\n");
return;
}
}
}
void find_book() {
int ISBN;
printf("Enter ISBN of book to find: ");
scanf("%d", &ISBN);
Book *temp = head;
while (temp != NULL && temp->ISBN != ISBN) {
temp = temp->next;
}
if (temp == NULL) {
printf("Book not found!\n");
return;
} else {
printf("Book name: %s\n", temp->name);
printf("Author name: %s\n", temp->author);
printf("ISBN: %d\n", temp->ISBN);
return;
}
}
void show_books() {
if (head == NULL) {
printf("Library is empty!\n");
return;
} else {
Book *temp = head;
while (temp != NULL) {
printf("Book name: %s\n", temp->name);
printf("Author name: %s\n", temp->author);
printf("ISBN: %d\n", temp->ISBN);
temp = temp->next;
}
}
}
int main() {
int choice;
while (1) {
printf("\n1. Add book\n");
printf("2. Delete book\n");
printf("3. Find book\n");
printf("4. Show all books\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
delete_book();
break;
case 3:
find_book();
break;
case 4:
show_books();
break;
case 5:
exit(0);
default:
printf("Invalid choice!\n");
break;
}
}
return 0;
}
```
该程序使用一个链表来保存所有的书籍,每个节点包含书名、作者、ISBN和指向下一个节点的指针。当用户添加一本书时,程序会在链表的末尾添加一个新节点。当用户删除一本书时,程序会遍历链表,找到要删除的节点并将其从链表中移除。当用户查找一本书时,程序会遍历链表,找到包含指定ISBN的节点并输出该节点的信息。当用户想要查看所有的书籍时,程序会遍历整个链表并输出每个节点的信息。