gpt4 book ai didi

c - 在c中递归地在末尾插入单链表

转载 作者:行者123 更新时间:2023-11-30 19:08:44 25 4
gpt4 key购买 nike

谁能告诉我我的代码有什么问题吗?
我想创建非返回函数 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;
}
}
}

最佳答案

您的代码太复杂,因此存在错误。例如存在内存泄漏。

您的意思似乎如下。

void insert_tail_Recursively( struct node **phead, int key )
{
if ( *phead == NULL )
{
*phead = malloc( sizeof( struct node ) );
( *phead )->data = key;
( *phead )->pLeft = ( *phead )->pRight = NULL;
}
else
{
phead = key < ( *phead )->data ? &( *phead )->pLeft : &( *phead )->pRight;
insert_tail_Recursively( phead, key );
}
}

关于c - 在c中递归地在末尾插入单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44531620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com