一、实验目的
掌握顺序存储的线性表的创建、查找、插入、删除和输出操作
二、实验内容
实现一个存放图书信息的顺序表
三、实验要求
- 图书的基本信息有图书编号(例如:1,2,3,4等),书名和价格等。
- 对图书的顺序表进行查找、插入、删除和输出操作。
(3)选做实验:把图书顺序表中的信息存储到文本文件,并且可以把文本文件中的图书信息存储到图书顺序表中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LIST_INIT_SIZE 100 //顺序表可能达到的最大长度100
typedef struct //书的结构体
{
char no[20]; //书的编号
char name[50]; //书名
float price; //书的价格
}Book;
void BookCreate(Book *bk, char no[], char name[], float price) //创建一本书
{
strcpy(bk->no,no);
strcpy(bk->name, name);
bk->price = price;
}
void BookPrint(Book bk) //输出书的信息
{
printf(bk.no);
printf("\t");
printf(bk.name);
printf("\t");
printf("%f",bk.price);
printf("\n");
}
typedef struct //顺序表
{
Book *elem; //存储空间的基地址
int length; //图书表中书的个数
}SqList;
int InitList(SqList *L) //初始化顺序表
{
L->elem = malloc(LIST_INIT_SIZE*sizeof(Book));
if(!L->elem)
{
printf("error initlist");
exit(1);
return 0;
}
L->length = 0;
return 1;
}
int ListPrint(SqList L) //输出顺序表中所有元素
{
int i = 0;
printf("The length of the list:%d\n",L.length);
printf("Books are: \n");
for(i=0;i<L.length;i++)
{
BookPrint(L.elem[i]);
}
printf("\n");
}
int ListInsert(SqList *L, int i, Book el) //在顺序表中插入元素
{
int location=i;
if(location>L->length+1||location<1)
{
return 0;
}
if(location>LIST_INIT_SIZE)
{
return 0;
}
for(i=L->length-1;location-1<=i;i--)
{
L->elem[i+1]=L->elem[i];
}
L->elem[location-1]=el;
L->length++;
return 1;
}
int ListDelete(SqList *L, int i) //删除第i个位置的元素
{
int location=i;
if(location>L->length+1||location<1)
{
return 0;
}
if(location>LIST_INIT_SIZE)
{
return 0;
}
for(;i<L->length;i++)
{
L->elem[i-1]=L->elem[i];
}
L->length--;
return 1;
}
int LocateElem(SqList L, char no[]) //在顺序表中找到编号为no的书的位置
{
int i=0;
for(i=1;i<=L.length;i++)
{
if(strcmp(L.elem[i-1].no,no)==0)
{
printf("LocateElem are:\n");
BookPrint(L.elem[i-1]);
printf("\n");
return i-1;
}
else
{
return;
}
}
}
int ModifyList(SqList *L, char newname[], char no[]) //把顺序表中编号为no的书名改成newname
{
strcpy(L->elem[LocateElem(*L,no)].name,newname);
return 1;
}
int main(void)
{
Book bk1,bk2;
SqList L;
BookCreate(&bk1,"NO00001","Data struct and algorithm",45.00);
BookCreate(&bk2,"NO00002","Data Minning",72.00);
BookPrint(bk1);
BookPrint(bk2);
InitList(&L);
ListInsert(&L, 1, bk1);
ListInsert(&L, 2, bk2);
ListInsert(&L, 4, bk2);
ListPrint(L);
ListDelete(&L,1);
ListDelete(&L,6);
ListPrint(L);
LocateElem(L,"NO00002");
LocateElem(L,"NO00003");
ModifyList(&L,"AI","NO00002");
ListPrint(L);
system("pause");
}