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

时间:2014-08-07 12:20:17

标签: c algorithm data-structures linked-list

我编写了下面的函数,使用用户定义的cmp函数将值按顺序插入到链表中。所以我测试了这个,我为整数编写了自己的cmp函数,并输入了值9和1.输出为9和1(它没有按顺序插入到链表中)。在调试了这个函数一段时间之后,我想如果(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;
}

1 个答案:

答案 0 :(得分:0)

插入此代码段

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;

可以对参数value进行另一个问题。它应该总是在堆中重新分配。您不能使用不同的值传递相同局部变量的地址。所以代码应该看作例如

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 );

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