尝试从c中的双链接列表中删除元素
在尝试从c中的双链接列表中删除元素时出现问题尝试从c中的双链接列表中删除元素,c,linked-list,double,C,Linked List,Double,在尝试从c中的双链接列表中删除元素时出现问题 Nodes_t *remove_Nodes (Nodes_t *a, Nodes_t b){ Nodes_t *head; head=a; if ((a->i_pos==b.i_pos) && (a->j_pos==b.j_pos)){ if (a->next=NULL){ return NULL; } else
Nodes_t *remove_Nodes (Nodes_t *a, Nodes_t b){
Nodes_t *head;
head=a;
if ((a->i_pos==b.i_pos) && (a->j_pos==b.j_pos)){
if (a->next=NULL){
return NULL;
}
else {
head=a->next;
head->previous=NULL;
return head;
}
}
else if ((a->i_pos!=b.i_pos) || (a->j_pos!=b.j_pos)){
while ((a->next->i_pos!=b.i_pos)||(a->next->j_pos!=b.j_pos)){
a=a->next;
if (a->next=NULL){
return head;
}
}
a=a->next;
a->previous->next=a->next;
if (a->next=NULL){
return head;
}
else if (a->next!=NULL){
a->next->previous=a->previous;
return head;
}
}
return head;
}
它获取一个双链接列表,查找Nodes\t类型的元素,然后将其删除。
虽然,正如我检查过的列表及其指针工作正常,但当我试图调用函数删除我的第一个元素时,我得到了一个seg错误
更具体地说,正如我已经检查过的,函数在达到这一点之前一直运行良好
else {
head=a->next;
head->previous=NULL;// HERE
return head;
}
我使用的结构是
typedef struct Nodes {
char position;
int i_pos, j_pos;
int g_distance;
int h_distance;
int F_estim;
struct Nodes *parent;
struct Nodes *next;
struct Nodes *previous;
}Nodes_t;
您在此处使用了赋值
=
而不是比较=
:
if (a->next=NULL){
它将计算为NULL
,这是false,因此将转到您的else
子句
head=a->next;
head->previous=NULL;
因此,head
变为NULL
,然后您试图取消对NULL
指针的引用,以获取其上一个成员
- 快速修复:将缺少的
=
添加到我引用的第一行
- 更好的解决方法:重构代码。它太长,有不必要的位。别忘了检查你的操作
父项、下一项、上一项、位置、i_位置和j_位置?这是什么样的“链表”?!经过三次阅读,我得出结论,代码可以减少到原来大小的一半以下。行数越少==出现错误的可能性越小==读取次数越少。(作为一个副作用,错误将浮出水面。在大多数情况下)下一个,以前的工作为“双链接列表”。其他变量和指针用于实现我试图制作的一个_星。很好!我忽略了它(由于对程序结构的追求…)谢谢你,我不能相信我错过了。。我也会尝试重构我的代码。