gpt4 book ai didi

c - 按顺序插入(链表C)错误

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

我编写了下面的函数,使用用户定义的 cmp 函数按顺序将值插入到链接列表中。所以我对此进行了测试,我为整数编写了自己的 cmp 函数,并输入值 9 和 1。输出是 9 和 1 (它没有按顺序插入到链表中)。在调试这个函数一段时间后,我发现 if(prev == NULL) 永远不会为真,因此我的程序被破坏了,我在这里做错了什么吗???,我们可以与 NULL 进行比较,对吗?

list_t *insert_in_order(list_t *list, void *value, int (*cmp)(void*,void*)) {

node_t *new_node, *curr, *prev;
new_node = (node_t *)malloc(sizeof(*new_node));
assert(new_node != NULL && list != NULL);
new_node->data = value;

/*Special case when the list is empty*/

if(list->head == NULL) {

new_node->next = NULL;
list->head = list->foot = new_node;

}

/*List is obviously not empty*/

else {

curr = list->head;
prev = NULL;

/*Traverse the list*/
while(curr) {

/*I am basically going to break the loop when I find the right position*/
/*to insert the node (after this node called prev)*/

if(cmp(curr->data, value) > 0) {
break;
}
prev = curr;
curr = curr->next;
}

/*So now I know the node will go after the prev (defined above) node.*/

/*Special case if this is the 0th position in the linked list i.e prev is null*/

if(prev == NULL) {
/*After doing some printfs here I see that prev is never null, anything*/
/*wrong here???????????*/
printf("prev is null\n");
new_node->next = list->head;
list->head = new_node;
}

else {
printf("prev is not null\n");
new_node->next = prev->next;
prev->next = new_node;
}
}
return list;
}

最佳答案

插入此代码片段

else {
printf("prev is not null\n");
new_node->next = prev->next;
prev->next = new_node;

以下声明

else {
printf("prev is not null\n");
new_node->next = prev->next;
prev->next = new_node;
if ( new_node->next == NULL ) list->foot = new_node;

另一个问题可以与参数相关。它应该总是在堆中重新分配。您不能传递具有不同值的同一局部变量的地址。所以代码应该看起来像

int *p = ( int * )malloc( sizeof( int ) );
*p = 9;

insert_in_order( list, p, cmp );

p = ( int * )malloc( sizeof( int ) );
*p = 1;

insert_in_order( list, p, cmp );

或者您必须在函数中分配传递值的副本。

关于c - 按顺序插入(链表C)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25182393/

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