#include <stdio.h> #include <malloc.h> #define MAX_LETTER 52 typedef struct tire { struct tire *next[MAX_LETTER]; char data; char cnt; }*_tire; void init_tire(_tire root, char *string) { _tire s; s=root; int pos; while (*string!= '/0' ) { if (*string>= 'A' && *string<= 'Z' ) pos = (*string - 'A' )*2; else pos = (*string - 'a' )*2 + 1; if (s->next[pos]==NULL) { s->next[pos] = (_tire)malloc( sizeof ( struct tire)); (s->next[pos])->data = *string; s = s->next[pos]; for ( int i=0;i<MAX_LETTER;i++) { s->next[i] = NULL; } } else { s = s->next[pos]; } string++; } s->cnt=1; } void print(_tire root, char *s, int i) { int j; s[i] = root->data; if (root->cnt==1) { s[i+1] = 0; puts(s); } for (j=0;j<MAX_LETTER;j++) { if (root->next[j]!=NULL) { print(root->next[j],s,i+1); } } } int searchtire(_tire root, char *tosearch) { int i; _tire p; if(*tosearch == '/0') return 0; for (i=0; i<MAX_LETTER; i++) { if (root->next[i] != NULL && (root->next[i])->data == *tosearch) { if((root->next[i])->cnt == 1 && *(tosearch+1) == '/0'){ return 1; }else return searchtire(root->next[i], tosearch+1); break; } } return 0; } int main() { _tire root; int m,i; char s[265]; root = (_tire)malloc( sizeof ( struct tire)); printf( "输入字符串个数:" ); for (i=0;i<MAX_LETTER;i++) { root->next[i]=NULL; } scanf( "%d" ,&m); getchar(); while (m--) { gets(s); init_tire(root,s); } puts( "/n依字典排序后:" ); for (i=0;i<MAX_LETTER;i++) { if (root->next[i] != NULL) { print(root->next[i],s,0); } } printf("查询:/n"); while(1){ gets(s); printf("%d/n", searchtire(root, s)); } return 0; }