这是一个片段。基本上,当我尝试运行这段代码时,它会崩溃。这个修改后的函数很可能是罪魁祸首(我以前用不同的方式写过它,但它工作得很好)。
Link *add_after(Link *p, Link *n,const string& s )
{
Link *current = p; //No 'previous' needed.
/* empty list */
if(p == 0){
cout<<"List is empty so string not found so nothing is added after it. \n";
return 0;
}
else if(p->value == s){ //Checks first Link.
cout << s << " was found in the Linked List. The new Link will be added.\n";
n->next = p->next;
p->next = n;
return p;
}
else{
current = current->next;
while(current != 0){ //Check the rest of the Linked List.
if(current->value == s){
cout << s << " was found in the Linked List. The new Link will be added.\n"; n->next = current->next;
current->next = n;
return p;
}
current = current->next; }
return 0;
}
} // end of function
最佳答案
除了在“当前”循环中找到匹配项后返回“p”外,我看不出有什么不妥。但是链表处理在我看来是正确的。然而,这个功能真的可以简化:
Link *add_after (Link *p,Link *n,const string &s)
{
for ( ; p != NULL; p = p->next) {
if (p->value == s) {
n->next = p->next;
p->next = n;
break;
}
}
return p;
}
关于c++ - 我的单链表中的一个函数(在找到特定节点后添加一个新节点)使我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033745/