【发布时间】:2015-04-01 15:27:53
【问题描述】:
我正在做一个项目,我将文本文件中的数据按顺序导入到链表中,然后输出链表。但是,每当我输出链表时,我总是会一遍又一遍地重复文本文件中的最后一个条目。
结构如下:
struct account
{
int accountNumber;
double balance;
string firstName;
string lastName;
account * next;
};
这是我在列表中添加节点的函数:
void insertAccountByAccountNumber(account * & H, account * n)
{
if (H == NULL)
{
H = n;
return;
}
if (H->accountNumber >= n->accountNumber)
{
n->next = H;
H = n;
return;
}
account * t1, *t2;
t1 = H;
t2 = H->next;
while (t2 != NULL)
{
if (t2->accountNumber < n->accountNumber)
{
t1 = t2;
t2 = t2->next;
}
else
{
n->next = t2;
t1->next = n;
return;
}
t1->next = n;
}
}
这是我从文本文件创建节点的代码:
account * head = NULL;
account * currentAccount = new account;
ifstream fin;
fin.open("record.txt");
while (fin >> accountNumberCheck)
{
fin >> firstNameCheck;
fin >> lastNameCheck;
fin >> balanceCheck;
currentAccount->accountNumber = accountNumberCheck;
currentAccount->firstName = firstNameCheck;
currentAccount->lastName = lastNameCheck;
currentAccount->balance = balanceCheck;
currentAccount->next = NULL;
insertAccountByAccountNumber(* & head, currentAccount);
}
showAccounts(head);
fin.close();
【问题讨论】:
-
您的问题解决了吗?
-
是的,我想通了。我非常感谢所有的帮助!
标签: c++ list pointers structure