JamesLiuxy


私信TA

用户名:usernames

访问量:2789

签 名:

等  级
排  名 34138
经  验 405
参赛次数 0
文章发表 3
年  龄 0
在职情况 学生
学  校 哈尔滨信息工程学院
专  业

  自我简介:

TA的其他文章

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


#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#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.length;i++){

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

 }

 t.length--;

 return t;

}



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

int SearchList(table t,char *elem){

            

for(int i=0;i<t.length;i++){

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

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

}

}

return -1;//没有找到 

}


//展示顺序表 

void display(table t){

    

for(int i=0;i<t.length;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;

}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区