# 手机号码查找算法（基数树）

600人阅读 评论(0)

typedef struct mctree_node      mctree_node;
struct mctree_node{
mctree_node     *child[10];     //节点内包含10个子节点
mctree_node     *parent;        //当前节点的父节点
dpl_uint8_t     level;          //当前节点深度
dpl_uint8_t     valid[10];      //每个子节点是否存在
//int           count[10];      //每个子节点计数器
};

typedef struct mctree_table      mctree_table;
struct mctree_table{
mctree_node     *root;
dpl_blkp_t      *blkp;
dpl_lock_t      lock;
};

dpl_status_t mcnode_find(mctree_node *root, char *id, mctree_node **valid, mctree_node **last)
{
mctree_node     *pt = NULL;
int             find = 0, i=0, j=0;

if(root == NULL || id == NULL || valid == NULL || last == NULL)
return EINVAL;
pt = *last =  root;

while(id[i] != '\0'){
j = id[i]-'0';
//若有效，则记录
if(pt->valid[j] == 1){
find  = 1;
*valid = pt;
}
//查找子节点
if(pt->child[j] != NULL){
pt = pt->child[j];
*last = pt;
}else{
break;
}
i++;
}

if(find == 1){
if((*valid)->level == strlen(id)-1)
return DPL_SUCCESS;
else
return DPL_ISCHILD;
}
return DPL_NOTFOUND;
}

dpl_status_t mcnode_add(mctree_table *mctree,char *id, mctree_node *last)
{
dpl_status_t    stat = DPL_SUCCESS;
mctree_node     *pt = NULL;
mctree_node     *pn = NULL;
int             i=0,j=0;

if(mctree == NULL || id == NULL)
return EINVAL;

if(last == NULL)
pt = mctree->root;
else
pt = last;

//查找待插入的子节点
while((id[i] != '\0') && (id[i+1] != '\0')){
j = id[i] - '0';
if(pt->child[j] == NULL){
stat = dpl_blkp_malloc(mctree->blkp, (void**)&pn);
if(DPL_SUCCESS != stat){
TRACE(dpl_blkp_malloc, stat);
return stat;
}
memset(pn, 0, sizeof(mctree_node));
pn->parent = pt; //新节点的父节点，此处用下标0
pn->level = pt->level + 1;
pt->child[j] = pn; //父节点子指向子节点
pt = pn;
}else{
pt = pt->child[j];
}
i++;
}
//插入
j = id[i] - '0';
if(pt->valid[j] == 1)
return DPL_EXIST;
pt->valid[j] = 1;
return DPL_SUCCESS;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：363535次
• 积分：4666
• 等级：
• 排名：第6501名
• 原创：95篇
• 转载：164篇
• 译文：0篇
• 评论：69条
评论排行
最新评论