2015-01-09 78 views
0

我将文本文件中的信息添加到节点中,然后创建一个链接列表,然后将其打印出来,但出现问题。我打印这些节点,结果非常完美,但是当我将它添加到列表中并打印出列表时,我得到了不断的重复,并且需要大约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; 
    } 
} 
+0

请查询可以回答的问题。 – 2015-01-09 19:39:48

回答

1

你每次打印出整个列表,你的元素添加进去。所以你实际上正在打印#elements阶乘线。将ustomerlist.print()移动到休息之前。

编辑 - 正如其他海报指出的那样,打印问题远离代码最重要的问题,但上述更改应该修复它。

+0

谢谢你多谢! :) – 2015-01-09 19:57:27

1

好吧,让我们列出一些眼前的问题:

在您分配内存并将其分配给padd功能,那么你就直接重新分配p以指向ustomer指向,使你失去你的记忆分配。

main函数中,你不应该做while(!in.eof()),因为eofbit标志没有设置,除非你试图从文件之外读取,否则你将迭代一次到多次。相反,例如

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

然后你把所有的最严重的问题:Undefined behavior,因为你有指针ustomer但你永远不初始化指针,你永远不会使它指向任何地方。

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

0

您提到打印功能在“继续”之前“重复”了信息。这是为什么:

当您添加更多的节点时,所有先前的节点将被打印出来,所以当您添加第N个节点时,您将打印(N^2)/ 2个项目,第M个节点重复NM次(它是二次方而不是阶乘)。所以你的时候有五个客户说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; 
     } 
    } 
}