简单顺序表实现
程序员文章站
2022-05-26 12:08:48
...
#include <stdlib.h>
#include <stdio.h>
#define MAX_LENGTH 20
typedef struct
{
char name[20];
double price;
}BOOK;
typedef struct
{
BOOK *list;
int length;
}Sqlist;
int InitList(Sqlist *); //初始化顺序表
void PrintList(Sqlist *); //打印顺序表
bool InsertIntoList(Sqlist *S,int pos); //在pos位置插入一个元素
bool DeleteFromList(Sqlist *S,int pos); //在pos位置删除一个位置
int main(void)
{
Sqlist S;
bool flag;
int num = InitList(&S);
// printf("num = %d\n",num);
// PrintList(&S);
// flag = InsertIntoList(&S,2);
// if(flag)
// printf("插入成功!\n");
// else
// printf("插入失败!\n");
PrintList(&S);
flag = DeleteFromList(&S,2);
if(flag)
printf("删除成功!\n");
else
printf("删除失败!\n");
PrintList(&S);
return 0;
}
bool DeleteFromList(Sqlist *S,int pos)
{
if(pos<0 || pos>S->length-1)
return false;
if(S->length==0)
return false;
for(int i=pos-1; i<S->length-1; ++i)
{
S->list[i] = S->list[i+1];
}
S->length--;
return true;
}
bool InsertIntoList(Sqlist *S,int pos)
{
if(pos<0 || pos>S->length)
return false;
if(pos>MAX_LENGTH-1)
return false;
if(S->length == MAX_LENGTH)
return false;
BOOK Q;
printf("输入数据\n");
printf("书名:");
scanf("%s",Q.name);
printf("价格:");
scanf("%lf",&Q.price);
for(int i=S->length-1; i>=pos-1; --i)
{
S->list[i+1] = S->list[i];
}
S->list[pos-1] = Q;
S->length++;
return true;
}
int InitList(Sqlist *S)
{
printf("书本数量:");
scanf("%d",&S->length);
S->list = (BOOK*)malloc(S->length*sizeof(BOOK));
for(int i=0; i<S->length; ++i)
{
getchar();
printf("输入第%d本信息\n",i+1);
printf("名称:");
scanf("%s",S->list[i].name);
printf("价格:");
scanf("%lf",&S->list[i].price);
}
return S->length;
}
void PrintList(Sqlist *Q)
{
int length = Q->length;
for(int i=0; i<length; ++i)
{
printf("第%d本书\n",i+1);
printf("名称:%s\n",Q->list[i].name);
printf("价格:%.2lf\n\n",Q->list[i].price);
}
}
下一篇: 2013中国云计算产业发展十大趋势