图书管理系统的设计与实现单链表
时间: 2023-08-14 10:05:28 浏览: 83
单链表实现图书管理系统方案.doc
好的,以下是一个使用单链表实现图书管理系统的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Book {
char name[50];
char author[50];
int year;
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 year of publication: ");
scanf("%d", &new_book->year);
new_book->next = head;
head = new_book;
}
void delete_book() {
char name[50];
printf("Enter book name to delete: ");
scanf("%s", name);
Book *current_book = head;
Book *previous_book = NULL;
while (current_book != NULL) {
if (strcmp(current_book->name, name) == 0) {
if (previous_book == NULL) {
head = current_book->next;
} else {
previous_book->next = current_book->next;
}
free(current_book);
printf("Book deleted successfully.\n");
return;
}
previous_book = current_book;
current_book = current_book->next;
}
printf("Book not found.\n");
}
void display_books() {
printf("Book List:\n");
Book *current_book = head;
while (current_book != NULL) {
printf("Book Name: %s\n", current_book->name);
printf("Author Name: %s\n", current_book->author);
printf("Year of Publication: %d\n", current_book->year);
current_book = current_book->next;
}
}
int main() {
int choice;
while (1) {
printf("\nMenu:\n");
printf("1. Add a book\n");
printf("2. Delete a book\n");
printf("3. Display all books\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_book();
break;
case 2:
delete_book();
break;
case 3:
display_books();
break;
case 4:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```
在上面的示例代码中,我们定义了一个 `Book` 结构体,该结构体包含了图书的名称、作者、出版年份,以及一个指向下一本书的指针。我们还定义了一个指向链表头部的指针 `head`。
在 `add_book` 函数中,我们创建了一个新的书籍节点,然后要求用户输入书籍的名称、作者和出版年份,并将该节点添加到链表的开头。
在 `delete_book` 函数中,我们要求用户输入要删除的书籍的名称,然后遍历链表查找该书籍。如果找到了该书籍,则将其从链表中删除。
在 `display_books` 函数中,我们遍历整个链表,并输出每本书的名称、作者和出版年份。
最后,在 `main` 函数中,我们使用一个循环来显示菜单,并根据用户的选择调用相应的函数。
阅读全文