用C语言1.初始化一个空的顺序表; 2.把这些图书导入顺序表,读出顺序表中图书总数,并输出所有图书信息; 3.删除第i(1<=i<=图书总数)本图书,并输出被删除的图书信息,输出删除第本图书后顺序表中剩余的图书信息。
时间: 2024-01-22 18:17:39 浏览: 70
1. 初始化一个空的顺序表可以使用以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 最大容量
typedef struct {
int bookId; // 图书编号
char bookName[20]; // 图书名称
float price; // 图书价格
} Book;
typedef struct {
Book books[MAX_SIZE]; // 存储图书的数组
int length; // 顺序表的长度
} SeqList;
SeqList* createSeqList() {
SeqList* list = (SeqList*)malloc(sizeof(SeqList));
list->length = 0;
return list;
}
```
2. 把这些图书导入顺序表,读出顺序表中图书总数,并输出所有图书信息可以使用以下代码:
```c
void addBook(SeqList* list, Book book) {
if (list->length == MAX_SIZE) {
printf("图书库已满,无法添加新图书!\n");
return;
}
list->books[list->length++] = book;
}
void printBooks(SeqList* list) {
printf("图书总数:%d\n", list->length);
for (int i = 0; i < list->length; i++) {
printf("编号:%d,名称:%s,价格:%.2f\n", list->books[i].bookId, list->books[i].bookName, list->books[i].price);
}
}
int main() {
SeqList* list = createSeqList();
Book book1 = {1, "Java程序设计", 49.9};
Book book2 = {2, "C语言程序设计", 39.9};
Book book3 = {3, "Python编程基础", 59.9};
addBook(list, book1);
addBook(list, book2);
addBook(list, book3);
printBooks(list);
return 0;
}
```
3. 删除第i(1<=i<=图书总数)本图书,并输出被删除的图书信息,输出删除第本图书后顺序表中剩余的图书信息可以使用以下代码:
```c
void deleteBook(SeqList* list, int index) {
if (index < 1 || index > list->length) {
printf("删除失败,图书编号无效!\n");
return;
}
Book book = list->books[index - 1];
for (int i = index; i < list->length; i++) {
list->books[i - 1] = list->books[i];
}
list->length--;
printf("已删除图书:编号:%d,名称:%s,价格:%.2f\n", book.bookId, book.bookName, book.price);
printBooks(list);
}
int main() {
SeqList* list = createSeqList();
Book book1 = {1, "Java程序设计", 49.9};
Book book2 = {2, "C语言程序设计", 39.9};
Book book3 = {3, "Python编程基础", 59.9};
addBook(list, book1);
addBook(list, book2);
addBook(list, book3);
printBooks(list);
deleteBook(list, 2);
return 0;
}
```
阅读全文