用C语言定义包含图书信息的顺序表和链表
时间: 2023-03-24 20:01:55 浏览: 130
C语言链表实现图书管理系统
您好!以下是使用C语言定义包含图书信息的顺序表和链表的示例代码:
1. 顺序表
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100 // 定义最大容量
typedef struct book {
char name[30];
char author[20];
float price;
} Book;
typedef struct sqList {
Book data[MAX_SIZE];
int length;
} SqList;
int main() {
SqList L;
L.length = 0;
// 插入元素
Book book1 = {"The Catcher in the Rye", "J.D. Salinger", 25.5};
L.data[L.length++] = book1;
Book book2 = {"To Kill a Mockingbird", "Harper Lee", 30.0};
L.data[L.length++] = book2;
// 遍历输出
for (int i = 0; i < L.length; i++) {
printf("书名:%s\n作者:%s\n价格:%.2f\n\n", L.data[i].name, L.data[i].author, L.data[i].price);
}
return 0;
}
```
2. 链表
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct book {
char name[30];
char author[20];
float price;
struct book *next;
} Book;
typedef struct linkedList {
Book *head;
int length;
} LinkedList;
int main() {
LinkedList L;
L.head = NULL;
L.length = 0;
// 插入元素
Book *book1 = (Book *)malloc(sizeof(Book));
strcpy(book1->name, "The Catcher in the Rye");
strcpy(book1->author, "J.D. Salinger");
book1->price = 25.5;
book1->next = NULL;
L.head = book1;
L.length++;
Book *book2 = (Book *)malloc(sizeof(Book));
strcpy(book2->name, "To Kill a Mockingbird");
strcpy(book2->author, "Harper Lee");
book2->price = 30.0;
book2->next = NULL;
book1->next = book2;
L.length++;
// 遍历输出
Book *p = L.head;
while (p != NULL) {
printf("书名:%s\n作者:%s\n价格:%.2f\n\n", p->name, p->author, p->price);
p = p->next;
}
// 释放内存
p = L.head;
while (p != NULL) {
Book *q = p;
p = p->next;
free(q);
}
return 0;
}
```
希望这个例子能帮到您!
阅读全文