gpt4 book ai didi

c - ,C, 尝试删除列表中的最后一个元素时崩溃

转载 作者:行者123 更新时间:2023-11-30 18:54:15 25 4
gpt4 key购买 nike

我的程序的目标是删除所有具有偶数值的元素。该程序工作正常,除非它应该删除最后一个元素:这会使程序崩溃。

我创建了一个具有以下结构的列表:

struct elemento{
int dato;
struct elemento *next;
};

您可以忽略列表的创建方式,因为我知道错误仅在此函数中:

struct elemento *eliminapari(struct elemento *p){

struct elemento * start = p;
struct elemento * temp, *temp2;
int cont;
cont = 0;
temp2 = p;
while(p != NULL && cont != 20){
temp2 = temp2->next;

if((p->dato % 2) == 0){
if (cont == 0){ //if first element
start = p->next;
free(p);
p = start;

}else if(p->next == NULL){ //if last element
temp2->next = NULL; //this would be the previous node
free(p);
p = NULL;

}else{
temp = p->next;
p->dato = p->next->dato;
p->next = p->next->next;
free(temp);

}
}else{printf("\n3\n"); p = p->next;}

cont = cont + 1;
}

return(start);

}

谢谢。

最佳答案

如果你调用 eliminapari 将 p 作为唯一的结构实例传递(换句话说,p->next 为 NULL),那么会发生什么。然后 while 循环中的第一行设置 temp2 == NULL。但是然后在您尝试在“else”子句中取消引用 temp2 (temp2->next = NULL),但 temp2 为 NULL,因此崩溃

关于c - ,C, 尝试删除列表中的最后一个元素时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com