我正在尝试创建一个程序,该程序将单词列表作为输入,并将它们分类到二叉树中,以便能够找到它们,例如,像一本字典。这是我到目前为止所做的,但我得到newEl -> el = input;
的分段错误我知道这是因为它试图指向一个NULL el,当树首次创建时,但我不知道是什么改进我的代码的最佳方法是。有人有主意吗?感谢。
struct node *tra(struct node * start, Type input) {
struct node * thisNode = start;
if (thisNode == NULL)
Type current = thisNode -> el;
if (strcmp(input, current) > 0)
return tra(thisNode -> right, input);
else if (strcmp(input, current) < 0)
return tra(thisNode -> left, input);
else
return thisNode;
}
}
Ta insert(Type input, Ta ta) {
if ((find(input, ta)) == FALSE) {
newEl -> el = input;
}
return ta;
}
Boolean find(Type input, Ta ta) {
if (tra(ta -> head, input) == NULL)
return FALSE;
}
答案 0 :(得分:0)
由于您已经知道问题所在,因此您应该解决它。分配节点并插入它。
Ta insert(Type input, Ta ta) {
if ((find(input, ta)) == FALSE) {
// call to tra will fail. this is the place to create a new node
struct node *newEl = (struct node*) malloc(sizeof(struct node));
newEl -> el = input;
newEl -> left = 0;
newEl -> right = 0;
// do the insertion ....
}
}
答案 1 :(得分:0)
好像你想要创建一个新节点,但我没有看到你为新节点分配空间的任何地方,例如:
newEl = (struct node*)malloc(sizeof(struct node));
祝你好运!
答案 2 :(得分:0)
这是指向等效指针的指针:
typedef char *Type;
struct node {
struct node *left , *right;
Type payload;
};
struct node **find_pp(struct node **pp, Type input) {
struct node *thisNode ;
while ( thisNode = *pp ) {
int diff;
diff = strcmp(input, thisNode->payload);
if (!diff) break;
pp = (diff <0) ? &thisNode->left : &thisNode->right;
}
return pp;
}
Boolean find(struct node *root, Type thing)
{
struct node **pp;
pp = find_pp( &root, thing);
return (*pp) ? True : False;
}
void insert (struct node **pp, Type thing)
{
struct node *newNode;
pp = find_pp (pp, thing);
if (*pp) return; /* already exists */
*pp = newNode = malloc (sizeof *newnode);
newNode->payload = strdup(thing);
newNode->left = NULL;
newNode->right = NULL;
return;
}
一些注释: