给定城市名称和头指针,代码应该在前一个节点参数之后添加一个节点。但是,当我运行代码时出现运行时错误,这是为什么?
city* addCity(city *head, city *previous, string cityName )
{
city* add = new city;
add->name=cityName;
add->next = NULL;
city* tmp = new city;
tmp = head;
if(tmp==NULL){
tmp = add;
}
while(tmp != NULL && tmp != previous){
tmp = head;
tmp = tmp->next;
}
if(tmp == previous){
add->next = previous->next;
tmp->next = add;
head = tmp;
return head;
}
}
最佳答案
while(tmp != NULL && tmp != previous){
tmp = head;
tmp = tmp->next;
}
这将无限次运行,因为在每次迭代中 tmp
都会重置为 head
。 tmp
只是在此循环中以循环方式在值 head
和 head->next
之间切换。
关于c++ - 在链表运行时错误中插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639043/