#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct BOOK{
char bname[100];
char bno[100];
}BOOK;
typedef struct BL{
BOOK *elem;
int len;
int listsize;
}BL;
//1初始化
bool initBL(BL &l){
l.len=0;
l.listsize=50;
l.elem=NULL;
l.elem=(BOOK*)malloc(sizeof(BOOK)*50);
if(l.elem==NULL){
return false;
}
return true;
}
//2任意位置插入
bool insertBL(BL& l,int n,BOOK b){
if(n<1||n>l.len+1||l.len>=l.listsize){
return false;
}
for(int i=l.len;i>=n;i--){
strcpy(l.elem[i].bname,l.elem[i-1].bname);
strcpy(l.elem[i].bno,l.elem[i-1].bno);
}
strcpy(l.elem[n-1].bname,b.bname);
strcpy(l.elem[n-1].bno,b.bno); /*写成 strcpy(l.elem[n-1].bname,b.bno);*/
l.len++;
return true;
}
//3任意位置删除
bool BLDelete(BL &l,int n){
if(n<1||n>l.len){
return false;
}
for(int i=n;i<l.len;i++){
strcpy(l.elem[i-1].bname,l.elem[i].bname); /*逻辑错误:写成 strcpy(l.elem[i-1].bname,l.elem[i].bname);*/
strcpy(l.elem[i-1].bno,l.elem[i].bno);
}
l.len--; /*忘记l.len--了*/
return true;
}
//4书号查找
bool searchByBno(BL l,char* s){
for(int i=0;i<l.len;i++){
if(strcmp(s,l.elem[i].bno)==0){
printf("已找到Bno为%s的书籍,bname为:%s,为表中第%d本\n",l.elem[i].bno,l.elem[i].bname,i+1);
return true;
}
}
printf("未找到Bno为%s的书籍\n",s);
return false;
}
//4书名查找
bool searchByBname(BL l,char* s){
for(int i=0;i<l.len;i++){
if(strcmp(s,l.elem[i].bname)==0){
printf("已找到Bname为%s的书籍,bno为:%s,为表中第%d本\n",l.elem[i].bname,l.elem[i].bno,i+1);
return true;
}
}
printf("未找到Bname为%s的书籍\n",s); /*忘记,s了;输出的好像是缓冲区的:printf("未找到Bname为%s的书籍\n");*/
return false;
}
//5制定位置查找
bool searchByNum(BL l,int num){
if(num<1||num>l.len)
return false;
printf("已找到第%d本书,bname为%s,bno为%s\n",num,l.elem[num].bname,l.elem[num].bno);
return true;
}
//7长度
int getLength(BL l){
printf("长度为:%d\n",l.len);
return l.len;
}
//8修改某条记录
bool listAlter(BL &l){
int choice;
int num;
printf("请输入要修改第几本书:\n");
scanf("%d",&num);
printf("要修改bname请按0,要修改bno请按1:\n");
scanf("%d",&choice);
if(choice==0){
printf("请输入修改后的bname:\n");
char name[100];
getchar(); /*又忘了在 gets()前面加getchar()吃回车*/
gets(name);
strcpy(l.elem[num-1].bname,name);
}
else if(choice==1){
printf("请输入修改后的bno:\n");
char no[100];
getchar();
gets(no);
strcpy(l.elem[num-1].bno,no);
}else
return false;
return true;
}
//9打印顺序表
void printBL(BL l){
printf("**********\nBookList:\n");
for(int i=0;i<l.len;i++){
printf("name: %-20s no: %-20s \n",l.elem[i].bname,l.elem[i].bno);
}
printf("**********\n");
}
int main(){
BL l;
BOOK b1={"哈利波特","120171"};
BOOK b2={"钢铁是怎样炼成的","110110"};
BOOK b3={"大家好,我是vae","057450"};
BOOK b4={"火影忍者","01100010"};
initBL(l);
insertBL(l,1,b1);
insertBL(l,1,b2);
insertBL(l,1,b3);
printBL(l);
insertBL(l,3,b4);
printBL(l);
BLDelete(l,3);
printBL(l);
searchByBno(l,"110110");
getLength(l);
searchByBname(l,"哈利波特");
listAlter(l);
printBL(l);
return 0;
}
顺序表
最新推荐文章于 2022-11-01 21:45:56 发布