我正在编写一个程序,在其中一个函数中,我必须从 LinkedList 中删除一个值
struct node *delete_val(int value, struct node *head) {
struct node *h1 = head;
if (head == NULL) { return NULL;}
if (head->next == NULL) { free(head); return NULL;}
while (h1 != NULL) {
if (h1->next != NULL && h1->next->data == value){
h1->next = h1->next->next;
} else {
h1 = h1->next;
}
free(h1);
return head;
}
}
如果通过:
(4,[3,4,5,6,4,4,7]);
函数应该返回:
[3,5,6,4,4,7]
但是我的函数出现了错误:
Error: the list returned by your function is invalid. The next field of node 0 is invalid (0xf5400650).
我基本上是在检查下一个节点是否在其“数据”(head->next->data) 中包含匹配值,如果是,我将重新切换当前链表的指针(head->next) 到它之后的那个 (head->next->next) 但我什至无法让它工作。
最佳答案
有两个问题。
- 您需要在更正链接后中断(因为您要删除一次值)
- 您正在释放错误的成员。
如果你把这两个都改正了,我觉得应该就可以了。
struct node *delete_val(int value, struct node *head) {
struct node *h1 = head;
struct node *tmp = NULL;
if (head == NULL) { return NULL;}
if (head->next == NULL) { free(head); return NULL;}
while (h1 != NULL) {
if (h1->next != NULL && h1->next->data == value){
tmp = h1->next;
h1->next = h1->next->next;
break;
} else {
h1 = h1->next;
}
}
free(tmp);
return head;
}
关于c - 仅删除一次具有特定值的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549095/