字典树

来源:互联网 发布:注射死刑 知乎 编辑:程序博客网 时间:2024/06/05 09:32

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


#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