[英]C++ Sorted Structure Linked List
我正在一个项目中,在该项目中,我将数据从文本文件中依次导入到链表中,然后输出链表。 但是,每当输出链接列表时,我总是得到文本文件中的最后一个条目,一遍又一遍地重复。
结构如下:
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();
您遇到的问题是,您仅在while循环之外创建一个节点,并且每次迭代都在重用它。 对于链接列表,每次插入列表时都需要创建一个新元素。
这是代码审查中的链表实现,您可以查看该实现以获取一些有关链表工作方式的指针。
正如Nathan所提到的,您需要为创建的每个数据条目分配额外的内存,并将其添加到链接列表中。 如果需要进一步改进,请执行以下操作:在将指针传递给函数时,实际上不需要附加的&符号,因为它已经是head数据的地址。 尝试:
account * head = NULL;
ifstream fin;
fin.open("record.txt");
while (fin >> accountNumberCheck)
{
fin >> firstNameCheck;
fin >> lastNameCheck;
fin >> balanceCheck;
account * currentAccount = new account; // Allocate a new memory location for each data entry in the heap
currentAccount->accountNumber = accountNumberCheck;
currentAccount->firstName = firstNameCheck;
currentAccount->lastName = lastNameCheck;
currentAccount->balance = balanceCheck;
currentAccount->next = NULL;
insertAccountByAccountNumber(head, currentAccount);
}
showAccounts(head);
fin.close();
当然,函数标头将是:
void insertAccountByAccountNumber(account * H,account * n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.