# include <stdio.h>
# include <string.h>
# include <stdlib.h>
typedef struct node{
int cnt;//标记从root->此节点 是否是一个完整的字符串
struct node*child[129];//以ascii码值作为下标
} Node;
Node*create_node()
{
int i;
Node*p;
p = (Node*)malloc(sizeof(Node));
p->cnt = 0;
for(i=0;i<129;i++)
{
p->child[i] = NULL;
}
return p;
}
void insert_node(Node*root,char* str)
{
Node*p;
char *s;
if(root == NULL || *str=='\0') //空字符 或者是 最上层的节点(也就是根节点)不存在
return;
s = str;
while(*s!='\0')
{
if(root->child[*s] == NULL)
{
p = create_node();
root->child[*s] = p;
root = root->child[*s];
}
s++;
}
root->cnt++;
}
void search_str(Node*root,char*str)
{
char *s;
if(root==NULL || *str=='\0')
{
printf("tire tree do not exist or string is null!!\n");
}
else
{
s = str;
while(*s != '\0')
{
if(root->child[*s]!=NULL)
{
root = root->child[*s];
}
else
{
break;
}
s++;
}
}
if(root->cnt != 0 )
{
if(*s == '\0')
{
printf("exist!!\n");
}
else
{
printf("not exist but is a prefix!!\n");
}
}
else
{
if(*s != '\0')
{
printf("not exit!!\n");
}
else
{
if(root->cnt == 0)
{
printf("not exist but is a prefix!!\n");
}
}
}
}
int main()
{
Node*root;
char str[100];
int n;
root = create_node();//开辟最上层的节点
scanf("%d",&n);
while(n--)
{
scanf("%s",str);
insert_node(root,str);
}
while((scanf("%s",str))!=EOF)
{
search_str(root,str);
}
return 0;
}
tire tree
最新推荐文章于 2023-05-04 00:50:57 发布