【发布时间】:2013-02-18 07:49:41
【问题描述】:
我正在尝试创建一个程序,该程序将单词列表作为输入,并将它们排序成二叉树,以便找到它们,例如像字典一样。这是我到目前为止所做的,但是我收到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;
}
【问题讨论】:
-
如果 find() 返回 false,tra 也将返回 NULL,并且对 newEl->XXX 的赋值将取消引用 NULL 指针。无论如何,最优雅的解决方案涉及到指针。
-
struct node *newEl = tra(ta -> head, input);将返回您现有的项目或 null。它永远不会给你一个指向新对象的指针。 -
我知道,但我不知道如何解决它
-
对不起,我开始看代码了。文字后来来了。 (我不喜欢文字 ;-)
-
似乎您想创建一个新节点,但我看不到您为新节点分配空间的任何地方(例如“newEl = (struct node*)malloc(sizeof(struct node) );").
标签: c binary-tree binary-search-tree