|
发表于 2018-10-17 22:03:44
|
显示全部楼层
修改指针内容用二级指针- #include <stdio.h>
- #include <stdlib.h>
- #define max_size 100
- typedef struct String
- {
- char a[max_size];
- int length;
- }String,*STRING;
- void initString(STRING *L) //3õê¼»ˉL
- {
- int i;
- printf("init length:");
- scanf("%d",&(*L)->length); //Õa¸öêÇêäèë3¤¶è
-
- printf("start key in char:");
- for(i = 1; i <= (*L)->length; i++)
- {
- scanf("%c",&(*L)->a[i]); //′óa¡¾1¡¿¿aê¼½øDDêäèë×Ö·û
- getchar();
- }
- }
- void get_next(STRING *L2,int next[])
- {
- int i=1,j;
- j = 0;
- next[1] = 0;
- while(i <= (*L2)->length)
- {
- if(j == 0 || (*L2)->a[i] == (*L2)->a[j])
- {
- i++;
- j++;
- next[i] = j;
- }
- else
- j = next[j];
- }
- }
- int KMP(STRING *L1,STRING *L2,int pos,int next[])
- {
- int i,j,flag = 0;
- i = pos;
- j = 1;
- while(i <= (*L1)->length && j <= (*L2)->length)
- {
- if(j == 0 || (*L1)->a[i] == (*L2)->a[j])
- {
- i++;
- j++;
- }
- else
- {
- j = next[j];
- }
- }
- if(i > (*L1)->a[0])
- {
- printf("KMP\n");
- exit(-1);
- }
- else
- return i-(*L2)->a[0];
- }
- int main()
- {
- int next[20];
- int pos,pos1;
- //char ch[20]="abcac";
- STRING L1;
- STRING L2;
- L1=(STRING)malloc(sizeof(String));
- L2=(STRING)malloc(sizeof(String));
-
- initString(&L1);
- printf("1\n");
- initString(&L2);
- get_next(&L2,next);
- printf("here\n:");
- scanf("%d", &pos);
- pos1=KMP(&L1,&L2,pos,next);
- printf("there\n",pos1);
- return 0;
- }
复制代码 |
|