通过一定的准则删除链表元素 [英] Delete element of linked list by a certain criterion
问题描述
我已经写了这个功能:
List* delPaintingCode(List* head, char *code)
{
List *p,*q;
for(p=head;p!=NULL;q=p,p=p->next)
{
if(!strcmp(code,p->code))
{
if (p==head)
{
q=head;
head=p->next;
free(q);
}
else
{
q->next=p->next;
free(p);
p=q;
}
}
}
return head;
}
,当我把它在另一个功能:
and when I call it in another function:
void delpainting()
{
char code[50];
printf("code ");
scanf("%s",code);
List *head=NULL;
head=delPaintingCode(filetolist,code);
}
程序崩溃等等。我有一个警告:通过delPainting code的参数1从兼容的指针类型
所以,我应该怎么字符串传递给函数?
So how should I pass the string to the function?
推荐答案
这导致崩溃的逻辑问题是的如果(P ==头)
枝您code:当你删除了最初的元素,释放头
而不更新 p
。这导致在很下一次迭代解引用一个释放的指针。
The logical problem that leads to a crash is in the if (p==head)
branch of your code: when you delete the initial element, you free the head
without updating p
. This leads to dereferencing a freed pointer on the very next iteration.
您可以通过引入一个假的节点与头
在接下来
,并返回<$解决问题C $ C>接下来,就像这样:
You can fix the problem by introducing a fake node with head
in its next
, and returning the next
, like this:
List fake;
fake.next = head;
// This loop always looks ahead by one element, i.e. at p->next.
for(List *p = &fake ; p->next != NULL ; p = p->next) {
if(strcmp(code, p->next->code)) {
continue;
}
List *q = p->next;
p->next = q->next;
free(q);
}
return fake.next;
本方法适用于初始元素,也因为我们增加了一个假头我们的名单,所以第一次围绕 P-&gt;接下来
是一样的头。这让我们统一治疗头元素和所有其他元素。
This approach works for the initial element, too, because we added a fake head to our list, so the first time around p->next
is the same as head. This lets us unify treatment of head element and all other elements.
这篇关于通过一定的准则删除链表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!