字典树

//字典树的插入和删除操作


#define MAX_SIZE 25

const int LinkSize = 27;
typedef enum {ELEM=0,BRCH}NodeType;
typedef struct
{
char ch[MAX_SIZE + 1];
int  curSize;
}KeyType;//关键码类型
typedef struct {}Record;
typedef struct
{
KeyType key;
Record  *recptr;
}ElemType;  //元素节点


struct TrieNode;
typedef struct
{
TrieNode * Link[LinkSize];
}BrchType; //分支节点

//字典树节点类型
typedef struct TrieNode
{
NodeType utype;
union
{
ElemType elem;
BrchType brch;
};
}TrieNode;


class TrieTree
{
private:
TrieNode *root;
static TrieNode* BuyNode()
{
TrieNode * s = (TrieNode*)malloc(sizeof(TrieNode) * 1);
if (s == NULL)return NULL;
memset(s, 0, sizeof(*s));
return s;
}
static TrieNode *BuyElem(ElemType x)
{
TrieNode *s = BuyNode();
if (s != NULL)
{
s->utype = ELEM;
s->elem = x;
}
return s;
}
static TrieNode* BuyBrch(TrieNode *&ptr, int pos)
{
TrieNode *s = BuyNode();
if (s != NULL)
{
s->utype = BRCH;
int index = FindIndex(ptr->elem.key, pos);
s->brch.Link[index] = ptr;
}
return s;
}
static void FreeNode(TrieNode *s)
{
free(s);
}


static int FindIndex(KeyType const x, int pos)
{
int index = 0;
if (x.curSize > pos)
{
index = x.ch[pos] - 'a' + 1;
}
return index;

}


//以下是插入操作,pos记录了匹配到的当前单词的字母位置

static bool Insert(TrieNode *&ptr, const ElemType &x,int pos)

{
bool res = false;
if (ptr == NULL)
{
ptr = BuyElem(x);
res = true;
}else if (ptr->utype == BRCH)
{
int index = FindIndex(x.key, pos);
res = Insert(ptr->brch.Link[index], x, pos + 1);
}else if(ptr->utype == ELEM)
{
if (strcmp(x.key.ch, ptr->elem.key.ch) != 0)
{
ptr = BuyBrch(ptr, pos);
int index = FindIndex(x.key, pos);
res = Insert(ptr->brch.Link[index], x, pos + 1);
}
}
return res;
}

//查找元素,相对简单
TrieNode* FindValue(TrieNode *ptr, KeyType x,int pos)
{
if (ptr == NULL)return NULL;
else if (ptr->utype == ELEM)
{
return strcmp(ptr->elem.key.ch, x.ch) == 0 ? ptr:NULL;
}
else if (ptr->utype == BRCH)
{
int index = FindIndex(x, pos);
return FindValue(ptr->brch.Link[index],x,pos + 1);
}
}
public:
TrieTree() :root(NULL){}
~TrieTree(){}
bool Insert(const ElemType &x)
{
bool rs = false;
if (x.key.curSize > 0)
{
rs = Insert(root, x,0);
}
return rs;
}


TrieNode *FindValue(KeyType x)
{
return FindValue(root, x,0);
}


bool Remove(const KeyType &x)
{
bool res = false;
TrieNode *s = FindValue(x);
if (s != NULL && s->utype==ELEM)
{
FreeNode(s);
s = NULL;
res = true;
}
return res;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值