【问题标题】:delete recursively number from linked list从链表中递归删除数字
【发布时间】:2016-06-01 16:43:31
【问题描述】:

大家好,我做了一个函数,它根据您要从链表中删除的数字递归地从链表中删除。但是在删除之后,如果我尝试打印列表它的堆栈并且存在运行时错误,因为在删除之后没有任何东西代替数字。如何完成代码?

 struct node* delete_item(struct node* head, int num)
{
    if (head == NULL) { // Found the tail
        printf("not found\n");
        return NULL;
    }
    else if (head->data == num) 
    { // Found one to delete
        head = head->next;
        free(head);
        printf("num founded");
        return head->next;
    }
    else 
    { // Just keep going
        head->next = delete_item(head->next, num);
        return head;
    }
}

【问题讨论】:

    标签: c recursion data-structures struct linked-list


    【解决方案1】:

    您释放了应该返回的内容,并取消了指向已释放内容的指针。这就是问题所在。

    你应该引入一个缓冲区来存储应该返回的内容。

    struct node* delete_item(struct node* head, int num)
    {
        if (head == NULL) { // Found the tail
            printf("not found\n");
            return NULL;
        }
        else if (head->data == num) 
        { // Found one to delete
            struct node* next = head->next;
            free(head);
            printf("num founded");
            return next;
        }
        else 
        { // Just keep going
            head->next = delete_item(head->next, num);
            return head;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 2021-12-20
      • 2016-07-19
      • 2020-05-14
      • 1970-01-01
      • 2012-11-06
      相关资源
      最近更新 更多