字典树问题,删除部分一定要注意取地址符, 详细说明见代码中的注释。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 20
string s;
struct node
{
node *next[30];
int Count;
node()
{
Count=0;
memset(next,0,sizeof(next));
}
};
node *root;
void Insert(string s1)
{
node *p;
p=root;
for(int i=0;i<s1.size();i++)
{
if(p->next[s1[i]-'a']==0)
{
p->next[s1[i]-'a']=new node();
}
p=p->next[s1[i]-'a'];
}
p->Count=1;
}
int Search(string s1)
{
node *p;
p=root;
int id;
int flag=0;
for(int i=0;i<s1.size();i++)
{
id=s1[i]-'a';
if(p->next[id]==0)
{
return 0;
}
if(i==s1.size()-1)
{
if(p->Count==1)flag=1;
for(int j=0;j<=25;j++)
{
if(p->next[j])flag=1;
}
if(flag==1)return 1;
else return 0;
}
p=p->next[id];
}
}
void Delete(node *&p,int cnt) //一定要加上取地址符,不然置为空时只是改变了
//当前指针的指向,而不是root后面的指针指向,<span style="white-space:pre"> </span>//因为这个WA了好多次
{
int i;
if(cnt==s.size())
{
p=NULL;
return;
}
int id=s[cnt]-'a';
if(p->next[id]==NULL)return;
Delete(p->next[id],cnt+1);
int flag=1;
for(i=0;i<26;i++)
{
if(p->next[i]!=NULL)
flag=0;
}
if(flag&&p->Count==0)p=NULL;
}
int main()
{
int N,i,j,flag;
string s1,s2;
cin.sync_with_stdio(false);
cin>>N;
root=new node();
for(i=1;i<=N;i++)
{
cin>>s1>>s2;
if(s1=="insert")
{
Insert(s2);
}
else if(s1=="search")
{
flag=Search(s2);
if(flag==1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else
{
s=s2;
Delete(root,0);
}
}
return 0;
}