c - 在链表的链表中插入元素
问题描述
我有以下结构:
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. 姓名 = Frank 3. 城市 = 示例 4. 电话 = 1111
客户 A 也有以下账户
账户 A:1. ID = 3333 2. 银行 = 示例 3. 类型 = 2 4. 余额 = 35.3
账户 B: 1. ID = 4444 2. 银行 = Exam 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 (...) 不间断。我该如何解决?
解决方案
您在代码中混合使用了 C++ 和 C,
new
您scanf
可以使用 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; }