2014-04-07 87 views
0

任何人都可以帮我指出并解释我在这个循环链表中的逻辑错误吗?提前致谢。C++循环链表错误

template <class xtype> 
void clist<xtype>:: copylist (const clist<xtype> & other) 
{ 
    node<xtype> *temp; 
    node<xtype> *p; 

    if (head !=NULL) 
     makeEmpty(); 
    if (other.head == NULL) 
     head = NULL; 
    else 
    { 
     p = other.head; 
     head = new node<xtype>; 

     head->info = p->info; 
     temp = head; 

     p = p->next; 

     while(p != head) 
     { 
      temp->next = new node<xtype>; 
      temp = temp->next; 
      temp->info = p->info; 
      p = p->next; 
     } 
     temp->next = head; 
    } 
} 

回答

0

只是快速看一下你的代码,我发现这一点:

while(p != head) 

您应该测试other.head,不head

+0

但为什么使用other.head而不是头? – user3504938

+0

@ user3504938因为'p'正在迭代'other'列表。 'head'本身就在你正在创建的列表中,而且不应该通过遍历'other'来遇到。 – paddy