大家好我做了一个函数,它根据你想从链表中删除的数字递归地从链表中删除。但是在删除之后,如果我试图打印列表的堆栈,并且出现运行时错误,因为在删除之后,数字的位置什么也没有。我怎样才能完成代码?
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;
}
}
最佳答案
您释放了应返回的内容并解除了指向已释放内容的指针的引用。这是错误的。
你应该引入一个缓冲区来存储应该返回的内容。
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;
}
}
关于c - 从链表中递归删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574396/