c++ - 在链表运行时错误中插入节点

标签 c++ algorithm linked-list

给定城市名称和头指针,代码应该在前一个节点参数之后添加一个节点。但是,当我运行代码时出现运行时错误,这是为什么?

 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 都会重置为 headtmp 只是在此循环中以循环方式在值 headhead->next 之间切换。

关于c++ - 在链表运行时错误中插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639043/

相关文章:

php - 获得给定数组中组合总和的最低价格

c++ - 为链表返回正确类型的迭代器

go - 在 Go 语言中返回其结构地址的方法

c++ - Qt4 + CGAL - "BOOST_JOIN"处的解析错误

C++ 容器类

c++ - Visual C++ 2010 多个项目的不同配置

algorithm - 适用于旅行商的 Harmony Search 算法

java - 将 Java 程序转换为 C++

python - 控制洗牌距离

java - 将两个链表的内容复制到java中的文本文件中