一本书的信息包括:书的ID,书名,价格。 请定义结构体类型表示书的信息并建立链表存储 若干本书籍。当输入ID为-1时表示输入结束。 输入110查找是否有该ID的书籍,若有,打印该 书的书名和价格。若无,则提示无此书。 删除一个已有书籍ID的相关信息。 插入一本书(111,"C Programming",32.5)到链表中 (假设链表中书的ID已有序并按照从小到大顺序) ,之后打印整个链表,显示该书信息已被正确插 入至链表。c语言写程序
时间: 2024-03-13 17:44:37 浏览: 171
以下是实现上述功能的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义书的信息结构体
struct Book {
int id;
char name[50];
float price;
struct Book *next;
};
// 查找指定ID的书籍
struct Book *find_book(struct Book *head, int id) {
struct Book *p = head;
while (p != NULL) {
if (p->id == id) {
return p;
}
p = p->next;
}
return NULL;
}
// 删除指定ID的书籍
void delete_book(struct Book **head, int id) {
struct Book *p = *head;
struct Book *prev = NULL;
while (p != NULL) {
if (p->id == id) {
if (prev == NULL) {
*head = p->next;
} else {
prev->next = p->next;
}
free(p);
printf("删除成功!\n");
return;
}
prev = p;
p = p->next;
}
printf("无此书!\n");
}
// 插入一本书
void insert_book(struct Book **head, int id, char *name, float price) {
struct Book *new_book = (struct Book *)malloc(sizeof(struct Book));
new_book->id = id;
strcpy(new_book->name, name);
new_book->price = price;
new_book->next = NULL;
struct Book *p = *head;
struct Book *prev = NULL;
while (p != NULL && p->id < id) {
prev = p;
p = p->next;
}
if (prev == NULL) {
new_book->next = *head;
*head = new_book;
} else {
prev->next = new_book;
new_book->next = p;
}
printf("插入成功!\n");
}
// 打印所有书籍信息
void print_books(struct Book *head) {
struct Book *p = head;
printf("ID\t书名\t\t价格\n");
while (p != NULL) {
printf("%d\t%s\t\t%.2f\n", p->id, p->name, p->price);
p = p->next;
}
}
int main() {
struct Book *head = NULL;
int id;
char name[50];
float price;
// 循环读入书籍信息并插入链表
while (1) {
printf("请输入书的ID(-1表示输入结束):");
scanf("%d", &id);
if (id == -1) {
break;
}
struct Book *book = find_book(head, id);
if (book != NULL) {
printf("已有该书,书名为%s,价格为%.2f元。\n", book->name, book->price);
continue;
}
printf("请输入书名:");
scanf("%s", name);
printf("请输入价格:");
scanf("%f", &price);
insert_book(&head, id, name, price);
}
// 查找书籍
printf("请输入要查找的书的ID:");
scanf("%d", &id);
struct Book *book = find_book(head, id);
if (book != NULL) {
printf("书名:%s,价格:%.2f元。\n", book->name, book->price);
} else {
printf("无此书!\n");
}
// 删除书籍
printf("请输入要删除的书的ID:");
scanf("%d", &id);
delete_book(&head, id);
// 插入一本新书
insert_book(&head, 111, "C Programming", 32.5);
// 打印所有书籍信息
print_books(head);
return 0;
}
```
注:上述代码中,使用了双重指针(`struct Book **head`)来表示链表头指针,这样可以在函数内部修改链表头指针的值,达到修改链表的目的。
阅读全文