我写了一个程序,通过双向链表的方式管理银行账户,但我发现注销程序有问题。
void suppCompte (int numCpt) {
CompteBancaire *pnt = first;
if (first==NULL) {
printf("la liste vide !\n");
}else{
while (pnt != NULL && pnt->idf.numCompte != numCpt) {
pnt=pnt->next;
if (pnt==first) { // Remove the first node
first=pnt->next;
free(pnt);
}else if (pnt->next==NULL) { // Remove the last node
pnt->prc->next=NULL;
free(pnt);
}else{ // Remove a moddle node
pnt->prc->next=pnt->next; // <==== !!!!
pnt->next->prc=pnt->prc; // <==== !!!!
free(pnt);
}
}
}
}我仍然有同样的问题,即使我尝试了这个方法:-(pnt->prc)->next=pnt->next;
发布于 2015-02-04 00:57:54
while循环之后的行会导致问题,即pnt=pnt->next应该在if-else if之后。因此,如果只有1个节点,则pnt将为空,这会导致else部分出现问题。修改后的代码为:
void suppCompte (int numCpt)
{
CompteBancaire *pnt=first;
if (first==NULL)
printf("la liste vide !\n");
else
{
while (pnt!=NULL && pnt->idf.numCompte!=numCpt)
CompteBancaire *temp=pnt;
if (pnt==first) // Remove the first node
{ first=pnt->next;
}
else if (pnt->next==NULL) // Remove the last node
{ pnt->prc->next=NULL;
}
else // Remove a moddle node
{ pnt->prc->next=pnt->next; <==== !!!!
pnt->next->prc=pnt->prc; <==== !!!!
}
pnt=temp->next;
free(temp);
}}
发布于 2015-02-04 01:16:52
检查您的指针以确保它们不为空。这可以通过两个简单的if循环来完成。在使用双向链表时,您必须始终注意这类事情,并且必须仔细考虑指令的顺序。
然后,在将指针设置为“指向”当前节点后,将当前节点的指针设置为NULL。
另外,考虑使用gdb。它是Gnu DeBugger。如果你用gcc编译,你可以说gcc -g <files and other stuff>用gdb调试符号编译。然后你可以在gdb中运行这个程序,检查变量的值,观察数据的求值,等等。你可能会找到很多关于这方面的好材料。
https://stackoverflow.com/questions/28303127
复制相似问题