从链接列表顺利打印节点

Printing nodes smoothly from linkedlist

本文关键字:打印 节点 链接 列表      更新时间:2023-10-16

我正在将文本文件中的信息添加到节点中,然后创建一个链表,然后将其打印出来,但是我遇到了问题。我打印节点,结果很完美,但是当我将其添加到列表中并打印出列表时,我不断重复,浏览列表大约需要 6 个小时,而最多需要 20 秒,它最终会浏览列表中的信息,但在继续之前会重复一些信息大约 500 次, 同时以相同的次数重复所有以前的信息。这是我的addprint函数:

void customerlist::add(customer* ustomer)
{
    customer* p = new customer;
    p = ustomer;
    p->next = NULL;
    if (head != 0)
    {
        curr = head;
        while (curr->next != NULL)
        {
            curr = curr->next;
        }
        curr->next = p;
        n++;
    }
    else
    {
        head = p;
    }
}
int customerlist::getLength()
{
    return n;
}
void customerlist::print()
{
    curr = head;
    while (curr != NULL)
    {
        cout << curr->ID << " ";
        cout << curr->name << "  " << curr->lastname << "  " << curr->town << endl;
        curr = curr->next;
    }
}

我的主要:

while (!in.eof())
{
    account* bank = new account;
    customer* ustomer; in >> ustomer->ID;
    // display number of customers
    if (ustomer->ID < 90000000)
    {
        count++;
        in >> ustomer->name >> ustomer->lastname >> ustomer->town;
        // cout << ustomer->ID<< " " << ustomer->name << "  " << ustomer->lastname<< "        "         << ustomer->town << endl ;
        ustomerlist.add(ustomer);
        ustomerlist.print();
    }
    else
    {
        break;
    }
}

每次向列表中添加元素时,您都会打印出整个列表。 所以你实际上是在打印 #elements 阶乘线。 将 ustomerlist.print() 移到中断之前。

编辑 - 正如其他海报所指出的那样,打印问题远非代码中最重要的问题,但上述更改应该可以解决它。

好的,让我们列出一些直接的问题:

add函数中,您分配内存并将其分配给p,然后直接重新分配p以指向ustomer指向的位置,从而使您丢失分配的内存。

main函数中,您不应该执行while(!in.eof()),因为直到您尝试从文件外部读取,才会设置eofbit标志,您将迭代一次到多次。相反,例如

while (in >> name >> lastname >> town) { ... }

然后你会遇到最糟糕的问题:未定义的行为,因为你有指针ustomer但你从不初始化那个指针,你永远不会让它指向任何地方。

最后一个问题的解决方案也可以解决第一个问题(内存泄漏):不要在add函数中分配阳极,而是在循环中分配一个节点,并在 add 函数中按原样使用它。

您提到打印功能在"继续"之前"重复"信息。原因如下:

当您添加

更多节点时,将打印出所有先前的节点,因此当您添加第 N 个节点时,您将打印 (N^2)/2 个项目,第 M 个节点重复 N-M 次(它是二次而不是阶乘)。因此,当您有五个客户说A B C D E,您将看到:

A 
A B 
A B C 
A B C D 
A B C D E 

相反,每次添加新节点时,请打印该新节点而不是整个列表。

在你的主逻辑中考虑这个逻辑:

main(){
    count = 0;
    tail = head;
    while (!in.eof())
    {
        customer *new_customer;
        in >>  new_customer->ID;
        //check ID against defined MAX instead of a hard coded #
        if(new_customer->ID < MAX_ID) {
            count ++;
            in >> new_customer->name >> new_customer->lastname >> new_customer->town;
            tail->next = new_customer;
            tail = tail->next;
            tail->next = NULL;
            // here, print each new node using cout, so you will have the complete list as you add
            cout << new_customer->name << " " << blah blah << endl;
            // unless there's a specific need to print the entire list every time, use:  
            // customerlist.print(); 
        }
        else {
            break;
        }
    }
}