基于顺序存储结构的图书信息表的逆序存储 代码
时间: 2023-12-19 15:05:50 浏览: 93
以下是基于顺序存储结构的图书信息表逆序存储的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 图书信息表最大容量
typedef struct {
int id; // 书籍编号
char name[20]; // 书籍名称
float price; // 书籍价格
} Book;
typedef struct {
Book data[MAXSIZE]; // 存储数据的数组
int length; // 当前存储的数据个数
} SeqList;
// 初始化图书信息表
void initList(SeqList *L) {
L->length = 0;
}
// 向图书信息表中添加一本书
void addBook(SeqList *L, Book book) {
if (L->length >= MAXSIZE) {
printf("Error: Book list is full!\n");
return;
}
L->data[L->length++] = book;
}
// 逆序存储图书信息表
void reverseList(SeqList *L) {
int i;
Book temp;
for (i = 0; i < L->length / 2; i++) {
temp = L->data[i];
L->data[i] = L->data[L->length - i - 1];
L->data[L->length - i - 1] = temp;
}
}
// 打印图书信息表
void printList(SeqList L) {
int i;
for (i = 0; i < L.length; i++) {
printf("Book %d: %s, %.2f\n", L.data[i].id, L.data[i].name, L.data[i].price);
}
}
int main() {
SeqList L;
initList(&L);
// 添加几本书
Book book1 = {1, "C Programming", 29.99};
addBook(&L, book1);
Book book2 = {2, "Data Structures", 44.99};
addBook(&L, book2);
Book book3 = {3, "Algorithms", 39.99};
addBook(&L, book3);
printf("Original Book List:\n");
printList(L);
printf("\nReversed Book List:\n");
reverseList(&L);
printList(L);
return 0;
}
```
该代码定义了一个 `Book` 结构体来存储每一本书的信息,以及一个 `SeqList` 结构体来存储整个图书信息表。其中,`initList()` 函数用于初始化图书信息表,`addBook()` 函数用于向图书信息表中添加一本书,`reverseList()` 函数用于逆序存储图书信息表,`printList()` 函数用于打印图书信息表。在 `main()` 函数中,我们添加了几本书,打印原始的图书信息表,逆序存储图书信息表并打印逆序后的结果。
阅读全文
相关推荐
















