当前位置: 首页 > 工具软件 > Big Bang > 使用案例 >

bangbang控制c语言代码大全,算法2-3~2-6:Big Bang (C语言代码)

阎经武
2023-12-01

解题思路:这道题其实考察就是顺序表的问题  只要会字符串匹配就行了。注意strcpy(a1,a2);a1和a2必须保证有一个是变量不能是常量。

return 0;这个得加上。

参考代码:

#include

#include

#include

#define Size 4

typedef struct List{

char a1[20];//存储字符串

}list;

typedef struct Table{

struct List *head;

int length;

int size;

}table;

table InitList(){

table t;

t.head=(list*)malloc(Size*sizeof(list));

if(!t.head){

printf("失败!");

exit(0);//申请失败退出

}

t.length=0;

t.size=Size;

return t;

}

//add是插入的位置   elem为插入的元素

table InsertList(table t,char *elem,int add){

if(add<1||add>t.length+1){

return t;

}

if(t.length>=t.size){

t.head=(list*)realloc(t.head,(t.size+1)*sizeof(list));

if(!t.head){

}

t.size+=1;

}

for(int i=t.length-1;i>=add-1;i--){

t.head[i+1]=t.head[i];

}

strcpy(t.head[add-1].a1,elem);

t.length++;

return t;

}

//add是要删除的位置

table deleteList(table t,int add){

if(add<1||add>t.length+1){

return t;

}

for(int i=add;i

t.head[i-1]=t.head[i];

}

t.length--;

return t;

}

//查找元素到底在哪个位置

int SearchList(table t,char *elem){

for(int i=0;i

if(strcmp(t.head[i].a1,elem)==0){

return i+1;//返回的是位置

}

}

return -1;//没有找到

}

//展示顺序表

void display(table t){

for(int i=0;i

printf("%s ",t.head[i].a1);

}

printf("\n");

}

int main(){

char str[80];

table t1=InitList();//初始化顺序表

while(scanf("%s",str)!=EOF){

if(strcmp(str,"insert")==0){

int n;

char str1[70];

scanf("%d",&n);

scanf("%s",str1);

t1=InsertList(t1,str1,n);

}

else if(strcmp(str,"delete")==0){

char str2[70];

scanf("%s",str2);

int s=SearchList(t1,str2);

if(s!=-1)

t1=deleteList(t1,s);

}

else if(strcmp(str,"search")==0){

char str3[60];

scanf("%s",str3);

int k=SearchList(t1,str3);

if(k!=-1)

printf("%d\n",k);

}

else{

display(t1);

}

}

return 0;

}

 类似资料: