C++排序结构链表

C++ Sorted Structure Linked List

本文关键字:链表 结构 排序 C++      更新时间:2023-10-16

我正在处理一个项目,我将文本文件中的数据按顺序导入到链表中,然后输出链表。但是,每当我输出链接列表时,我总是让文本文件中的最后一个条目一遍又一遍地重复。

结构如下:

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循环之外创建一个节点,并且每次迭代都要重用它。使用链表,每次插入列表时都需要创建一个新元素。

下面是一个正在进行代码审查的链表实现,您可以查看它来获得关于链表如何工作的一些指针。