我具有以下结构:
typedef struct trans {
int code;
int issuersAccsID;
double amount;
int type;
char date [100];
int secondPartysId;
char description [41];
trans *next;
} transaction;
typedef struct acct{
int id;
char bank [50];
int type;
double balance;
acct *next;
transaction *tnext;
} account;
struct client{
int id;
char name [150];
char city [200];
char phone [30];
client *next;
account *anext;
};
当我在“客户”列表中插入元素时,它工作正常,但问题出在我进入“子列表”时,因为它无限插入最后一个元素。
void fileExists(client **p){
client *ax = new client, *t = *p;
scanf("%d",ax->id);
scanf("%s",ax->name);
ax->city="Example";
scanf("%s",ax->phone);
if (t==NULL)
*p=ax;
else{
/*Insert at the end of the list*/
t = *p;
ax->next = NULL;
while(t->next != NULL)
t=t->next;
t->next = ax;
}
/************************* ACCOUNTS ******************************/
scanf("%d",auxid);
scanf("%s",auxb);
scanf("%d",auxt);
scanf("%lf",auxbal);
/*Insert at the end of the list*/
ax->anext = new account;
t = *p;
t->anext = (*p)->anext;
ax->anext->id = auxid;
strcpy(ax->anext->bank,auxb);
ax->anext->type = auxt;
ax->anext->balance = auxbal;
ax->anext->next = NULL;
if (t->anext == NULL)
(*p)->anext = ax->anext;
else while(t->anext->next != NULL)
t->anext=t->anext->next;
t->anext->next = ax->anext;
}
为了更好地解释正在发生的事情,假设我们插入了2个客户端
客户A: 1. ID = 4 2.名称=弗兰克 3.城市=示例 4.电话= 1111
客户A也具有以下帐户
帐户A: 1. ID = 3333 2.银行=示例 3.类型= 2 4.余额= 35.3
帐户B: 1. ID = 4444 2.银行=考试 3.类型= 1 4.余额= 38.3
客户B: 1. ID = 6 2.名称= Riley 3.城市=示例 4.电话= 2222
客户B也有以下帐户
帐户A: 1. ID = 6666 2.银行= Ex 3.类型= 2 4.余额= 77.3
帐户B: 1. ID = 8888 2.银行= E 3.类型= 1 4.余额= 7542.3
帐户C: 1. ID = 9998 2.银行= Ex 3.类型= 2 4.余额= 752.63
当我完成在链接列表中的插入后,客户A 的帐户列表如下所示:
帐户B->帐户B->帐户B->帐户B(...)不间断。我该怎么解决?
答案 0 :(得分:2)
您在new
和scanf
的代码中混合使用了C ++和C语言,可以使用malloc,如下面的示例所示
在结构声明中,给出的代码将无法编译。 trans *next;
应该更改为struct trans *next;
。同样将acct *next;
更改为struct acct *next;
在客户案例中,您还应该为案例ax->next = NULL
设置(t == NULL)
对于插入帐户,我在客户案例中使用了ax
变量来修改了代码,如下所示。
account * acc = malloc (sizeof (account));
account * acc2;
if (acc == NULL) { exit (1); } // or any other method to handle memory error
scanf("%d",acc->code);
scanf("%s",acc->bank);
scanf("%d",acc->type);
scanf("%lf",acc->balance);
acc->next = NULL;
if (ax->anext == NULL)
{
ax->anext = acc;
}
else
{
acc2 = ax->anext;
while (acc2->next != NULL)
{
acc2 = acc2->next;
}
acc2->next = acc;
}