请用C语言实现并写上注释:定义一个包含图书信息(书号、书名、价格)的链表,完成以下操作: 1. 图书信息表的创建(使用头插法)和输出 2. 图书信息表的新图书的入库 3. 图书信息表的旧图书出库 4. 图书信息表的按书号查找 以上功能用线性表的链式结构完成
时间: 2023-12-09 21:57:41 浏览: 165
C语言实现的双链表功能完整示例
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义一个图书结构体,包含书号、书名、价格
typedef struct Book {
char id[20];
char name[50];
float price;
struct Book *next;
} Book;
// 头插法创建链表
Book *createBookList() {
Book *head = NULL; // 定义头节点
char id[20], name[50];
float price;
while (1) {
printf("请输入书号:");
scanf("%s", id);
if (strcmp(id, "0") == 0) {
break;
}
printf("请输入书名:");
scanf("%s", name);
printf("请输入价格:");
scanf("%f", &price);
// 创建新节点
Book *newNode = (Book*)malloc(sizeof(Book));
strcpy(newNode->id, id);
strcpy(newNode->name, name);
newNode->price = price;
// 头插法插入新节点
newNode->next = head;
head = newNode;
}
return head;
}
// 输出链表中的所有图书信息
void printBookList(Book *head) {
printf("图书信息如下:\n");
printf("%-20s%-50s%-10s\n", "书号", "书名", "价格");
while (head != NULL) {
printf("%-20s%-50s%-10.2f\n", head->id, head->name, head->price);
head = head->next;
}
}
// 入库操作
void addBook(Book **head) {
char id[20], name[50];
float price;
printf("请输入书号:");
scanf("%s", id);
// 查找该书是否已经存在
Book *p = *head;
while (p != NULL) {
if (strcmp(p->id, id) == 0) {
printf("该书已经存在!\n");
return;
}
p = p->next;
}
printf("请输入书名:");
scanf("%s", name);
printf("请输入价格:");
scanf("%f", &price);
// 创建新节点
Book *newNode = (Book*)malloc(sizeof(Book));
strcpy(newNode->id, id);
strcpy(newNode->name, name);
newNode->price = price;
// 头插法插入新节点
newNode->next = *head;
*head = newNode;
printf("入库成功!\n");
}
// 出库操作
void deleteBook(Book **head) {
char id[20];
printf("请输入要出库的书号:");
scanf("%s", id);
Book *p = *head;
Book *pre = p;
while (p != NULL) {
if (strcmp(p->id, id) == 0) {
if (p == *head) { // 如果是头节点
*head = p->next;
} else {
pre->next = p->next;
}
free(p); // 释放节点空间
printf("出库成功!\n");
return;
}
pre = p;
p = p->next;
}
printf("没有找到该书!\n");
}
// 按书号查找
void searchBook(Book *head) {
char id[20];
printf("请输入要查找的书号:");
scanf("%s", id);
while (head != NULL) {
if (strcmp(head->id, id) == 0) {
printf("%-20s%-50s%-10.2f\n", head->id, head->name, head->price);
return;
}
head = head->next;
}
printf("没有找到该书!\n");
}
int main() {
Book *head = NULL;
int choice;
while (1) {
printf("\n");
printf("1. 创建图书信息表\n");
printf("2. 新图书入库\n");
printf("3. 旧图书出库\n");
printf("4. 按书号查找\n");
printf("0. 退出\n");
printf("请选择操作:");
scanf("%d", &choice);
switch (choice) {
case 1:
head = createBookList();
printBookList(head);
break;
case 2:
addBook(&head);
printBookList(head);
break;
case 3:
deleteBook(&head);
printBookList(head);
break;
case 4:
searchBook(head);
break;
case 0:
return 0;
default:
printf("输入错误,请重新输入!\n");
break;
}
}
return 0;
}
```
阅读全文