【发布时间】:2017-06-13 21:09:24
【问题描述】:
谁能告诉我我的代码有什么问题?
我想创建非返回函数void 在链表末尾插入一个节点。
void insert_tail_Recursively(struct node **phead, int key) {
if (*phead == NULL) {
Node*temp = malloc(sizeof(Node));
temp->data = key;
temp->pLeft = temp->pRight = NULL;
*phead = temp;
} else {
Node*temp = malloc(sizeof(Node));
temp->data = key;
temp->pLeft = temp->pRight = NULL;
/* data more than root node data insert at right */
if ((temp->data > (*phead)->data) && ((*phead)->pRight != NULL))
insert_tail_Recursively((*phead)->pRight, key);
else if ((temp->data > (*phead)->data) && ((*phead)->pRight == NULL)) {
(*phead)->pRight = temp;
}
/* data less than root node data insert at left */
else if ((temp->data < (*phead)->data) && ((*phead)->pLeft != NULL))
insert_tail_Recursively((*phead)->pLeft, key);
else if ((temp->data < (*phead)->data) && ((*phead)->pLeft == NULL)) {
(*phead)->pLeft = temp;
}
}
}
【问题讨论】:
-
这个条件 temp->data data 是什么意思?它与“列表末尾”有什么关系?
-
你遇到了什么错误?
-
您正在询问添加到列表中,但代码是关于添加到树中。没有
struct node的定义。即使添加它,代码也无法正确编译。请修复编译错误,它们在这里有意义。 -
您不应该递归地执行此操作。如果您的列表很大,您肯定会破坏堆栈。
标签: c tree insert binary-tree