一个本来应该很简单的单词查找树,但是这里的实现有问题,问题是我不知道错在那里,能有大神指出问题所在么?谢过~
A simple trie , but below implement is wrong . Unfortunately I don't know where the error is ... Could You Help Me?Thanks~
头文件
#include <stdlib.h>
#include <string.h>
#define ALPHA 26
typedef struct Node{
int value;//最后的键值
// 指向下一个Node的指针数组
struct Node *next[ALPHA];
} Node;
Node * createNode();
Node * getTrieIn(Node * x,char * key,int d);
Node * putTrieIn(Node * x,char * key,int value,int d);
extern int getIn(Node * root,char * key);
extern void putIn(Node * root,char * key,int value);
主体文件
#include <stdio.h>
#include "trie.h"
Node * createNode(){
Node * node = (Node *)malloc(sizeof(Node));
int i;
for(i=0;i<ALPHA;i++)
node->next[i] = NULL;
return node;
}
int getIn(Node * root,char * key){
Node * x = getTrieIn(root,key,0);
if (x == NULL) return 0;
return x->value;
}
Node * getTrieIn(Node * x,char * key,int d){
if(x == NULL) return 0;// It mains the word not in the dir
if(d == strlen(key)) return x;// find it
char c = *(key + d);// root node not contain alpha
getTrieIn(x->next[c-'a'],key,d+1);
}
void putIn(Node * root,char * key,int value){
putTrieIn(root,key,value,0);
}
Node * putTrieIn(Node * x,char * key,int value,int d){
// 通过这个关联两个结点
if(x == NULL) x = createNode();
if(d == strlen(key)){
x->value = value;
printf("find it:%d\n",x->value);
return x;
}
char c = *(key +d);
printf("print c:%c\n",c);
return putTrieIn(x->next[c-'a'],key,value,d+1);
}
int main(void){
Node * root = createNode();
putIn(root,"string",1);
int a = getIn(root,"string");
printf("Can I find the value?:%d\n",a);
int i = 0;
for(i;i<ALPHA;i++){
int b = (root->next[i] == NULL);
//printf("has NULL?:%d\n",b);
}
return 0;
}