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

标签 c algorithm data-structures linked-list

我编写了下面的函数,使用用户定义的 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/

相关文章:

c - 合并两个链表

c - 从客户端发送结构并使用 SUN-RPC 将结构保存到链表中的服务器

将整数与整数数组的元素进行比较

c++ - 如何在 spidermonkey 嵌入中提供 js-ctypes?

algorithm - 以下代码片段的时间复杂度?

Java:如何考虑对马尔可夫链建模?

c - 具有递归功能的 10 基的基数转换器 - C

c# - 删除其中一条后对剩余记录重新编号

algorithm - 如何优化返回正整数 x 值的算法,使得 f(x) >=0 对于部分已知函数?

algorithm - 线段树内存