【发布时间】:2021-02-22 07:39:15
【问题描述】:
我已经实现了一个 trie 数据结构 (reference)。当我插入数据结构时,出现分段错误。这可能是语义错误。请帮忙改正。
#include <stdio.h>
#include <stdlib.h>
#define maxlength 10
typedef struct node {
int isend;
struct node *branch[27];
} trinode;
int count, len;
trinode *createnode() {
trinode *new = (trinode *)malloc(sizeof(trinode));
int ch;
for (ch = 0; ch < 26; ch++) {
new->branch[ch] = NULL;
}
new->isend = 0;
}
trinode *insert_trie(trinode *root, char *newenty) {
int ind;
trinode *proot;
if (root == NULL)
root = createnode();
proot = root;
for (int i = 0; i < maxlength; i++) {
ind = newenty[i] - 'a';
if (newenty[i] == '\0')
break;
else {
if (root->branch[ind] == NULL)
root->branch[ind] = createnode();
root = root->branch[ind];
}
if (root->isend != 0)
printf("trying to insert duplicate");
else
root->isend = 1;
return proot;
}
}
void print_trie(trinode *cur) {
char word[40];
for (int i = 0; i < 26; i++) {
if (cur->branch[i] != NULL) {
word[count++] = (i + 'a');
if ((cur->branch[i]->isend) == 1) {
printf("\n");
for (int j = 0; j < count; j++) {
printf("%c", word[j]);
}
}
print_trie(cur->branch[i]);
}
}
count--;
}
int search_trie(trinode *root, char *target) {
int ind;
for (int i = 0; i < maxlength && root; i++) {
ind = target[i] - 'a';
if (target[i] == '\0')
break;
else
root = root->branch[ind];
}
if (root && root->isend == 1)
return root;
else
return 0;
}
int main() {
int ch;
trinode *root = NULL;
char *newenty;
char *target;
int check;
while (1) {
printf("\n enter option 1.insert_trie 2.display 3.search 4.exit");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("enter word");
scanf("%s", newenty);
root = insert_trie(root, newenty);
break;
case 2:
count = 0;
print_trie(root);
break;
case 3:
printf("enter elem you want to search");
scanf("%s", target);
check = search_trie(root, target);
if (check == 0)
printf("word not found");
else
printf("found");
break;
case 4:
exit(0);
break;
}
}
}
【问题讨论】:
标签: c struct tree definition trie