C++排序结构链表
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();
正如Nathan所提到的,您需要为创建并添加到链表中的每个数据条目分配额外的内存。如果您需要进一步改进,这里有一个:您实际上并不需要额外的"&"符号,因为它已经是头数据的地址。尝试:
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);
您面临的问题是,您只在while循环之外创建一个节点,并且每次迭代都要重用它。使用链表,每次插入列表时都需要创建一个新元素。
下面是一个正在进行代码审查的链表实现,您可以查看它来获得关于链表如何工作的一些指针。
相关文章:
- 链表,反向函数,数据结构
- 我对数据结构、双向链表有一些问题
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 使用链表数据结构打印多项式
- C++:如何做一个链表,结构作为参数传递?
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 在排序链表中插入结构并将其写入二进制文件
- 具有多个结构的链表
- 使用带有结构结构作为 C++; 元素的单向链表
- 如何从文件读取到动态分配的指向结构的指针链表中?
- 结构内具有更多数据类型的单个链表
- 尝试连接两种不同类型的结构来创建链表
- C++中的数据结构,插入链表中节点的开头
- 链表结构(将结构指针传递给函数)
- 使用链表结构 C++ 将值推送到堆栈类
- 如何在C++中将链表结构返回到main
- 链表结构推送和弹出
- 删除链表结构的链表