嗨,我在 C 中实现了一个 trie ...但我在 insert_trie 函数中遇到了一个错误。
我无法弄清楚为什么根节点没有得到更新。请帮我解决一下这个。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct
{
char value;
int level;
struct node *next;
struct node *list;
}node;
node *trie = NULL;
node *init_trie()
{
node *new = (node *)malloc(sizeof(node));
if(trie == NULL)
{
new->value = '$';
new->next = NULL;
new->list = NULL;
new->level = 0;
trie = new;
printf("\n Finished initializing the trie with the value %c",trie->value);
return trie;
}
printf("\n Trie is already initialized");
return trie;
}
node *insert_trie(char *s)
{
node *nodepointer = trie;
node *new = (node *)malloc(sizeof(node));
node *save = NULL;
int i=0;
while(s[i]!=NULL)
{
nodepointer = nodepointer->list;
while(nodepointer!=NULL)
{
if(s[i] == nodepointer->value)
{
printf("\n Found %c",nodepointer->value);
nodepointer = nodepointer->list;
i++;
}
save = nodepointer;
nodepointer = nodepointer->next;
}
new->value = s[i];
new->next = NULL;
new->list = NULL;
printf("\n Inserting %c",new->value);
save->next = new;
i++;
}
return trie;
}
int main()
{
int num;
char *s = (char *)malloc(sizeof(char)*10);
trie = init_trie();
printf("\n Enter the number of words to enter into the trie ");
scanf("%d",&num);
while(num>0)
{
scanf("%s",s);
//printf("%s",s);
trie = insert_trie(s);
printf("\n Finished inserting the word %s into the trie \n",s);
num --;
}
return 0;
}
由于 insert_trie 函数中的行 nodepointer = nodepointer->list 导致分段错误...为什么 ????
PS:这不是作业。但我正在尝试实施它。我只是找不到错误。