1003

字典树问题,删除部分一定要注意取地址符, 详细说明见代码中的注释。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值