提前谢谢了!
因此,我尝试使此功能正常工作。函数中有错误,但无法捕获。
在我看来,我已经错过了排序的逻辑。
您能指出我要去哪里吗?
/* node*/
typedef struct client {
int number; /* */
int balance;/* */
char lastName[20]; /* */
char firstName [20];/* */
char phone[11]; /* */
char email[20];
struct client *prev;/* */
struct client *next;
struct client *tmp; /* */
} Client;
Client *firstc,*currentc,*newc, *a, *b,*tmp; /*pointers*/
/* *"firstc' firstc element in list
*'currentc' current node
*'newc' new node
*'a' temporary pointer to Sort function
*'b' temporary pointer to Sort function
*'tmp' temporary pointer to Sort function
*/
int counter = 0;
int cnum = 0; /*cnum gives unique account numbers avoiding misentering*/
/*---Sort function------*/
void Sort()
{
/* */
int a = 0;/*variables to store balance*/
int b = 0;/*variables to store balance*/
if(firstc==NULL)
printf("Database is empty"); /*message*/
else
currentc = firstc;
currentc->prev = NULL;
tmp = NULL;
while((currentc=currentc->next)!= NULL)
{ /* 1) compare two nodes;
2) IF balance >*/
int a = currentc->balance;
int b = currentc->next->balance;/* debugger stopped here... */
if (a>b)
//if(currentc->balance >currentc->next->balance)
{ /*swap nodes*/
/*code using three pointers*/
tmp = currentc->next;
currentc->next->next = currentc->next;
currentc->next->next = tmp;
}
/*3)move along the list*/
else
currentc = currentc->next;
/*4) repeat to the end of list*/
}
currentc = firstc;
listAll();
return;
}
最佳答案
int b = currentc->next->balance;/* debugger stopped here... */
当
currentc
指向列表中的最后一项时,currentc->next
将为null。因此,currentc->next->balance
是通过空指针进行的访问。同样,在
while((currentc=currentc->next)!= NULL)
这样的条件下进行赋值之类的做法最终会再次伤害您。在这种情况下,您似乎跳过了列表中的第一项。您可能的意思是:
if(firstc == NULL)
printf("Database is empty"); /*message*/
else
{ /* missing braces spotted by others */
currentc = firstc;
currentc->prev = NULL;
tmp = NULL;
for( ; currentc != NULL; currentc = currentc->next)
{
if(currentc->next == NUL)
/* nothing to compare */
break;
...
}
}
此外,交换代码正在交换错误的节点:
tmp = currentc->next;
currentc->next->next = currentc->next;
currentc->next->next = tmp;
将几乎(但不太完全)交换下一个节点(b),与其后的节点交换(a)。您需要使用
prev
指针(但是,由于这看起来像作业,所以最好不要告诉您确切的操作方法)。另外,您正在初始化prev
,但需要在循环中保持最新状态。实际上,您上面的3行等效于: tmp = currentc->next;
currentc->next->next = tmp;
所以我想你的意思是别的。