c++ - 链表头指针在传递给函数 c++ 时发生变化

标签 c++ pointers linked-list

<分区>

我的二年级编程课有一个问题,涉及创建一组双向链表来表示医院以及医院中的医生和患者。一家医院有一份医生名单,每个医生都有一份病人名单。我的问题是,当我调用“hireDoctor”函数将医生添加到医院列表时,头指针不知何故发生了变化。这是我的代码:

    /* adds a Doctor to the Hospital's list of Doctors */
    void Hospital::hireDoctor(Doctor *doc)
    {
        DoctorNode node;
        node.value = *doc;
        DoctorNode* curr;

        if (drListHead == NULL) {    //if doctor list is empty,
            drListHead = &node;    //insert the node at the beginning
            node.next = NULL;
            node.prev = NULL;
        } else {
            curr = drListHead;
            //traverse list until equal or greater (alphabetical) value is found:
            while (curr->value.getLast().compare(node.value.getLast()) < 0 &&
            curr->value.getFirst().compare(node.value.getFirst()) < 0) {
                curr = curr->next;
            }
            if (curr->prev == NULL) {     //if inserting at the beginning of the list
               drListHead = &node;
               node.prev = NULL;
               node.next = curr;
            } else if (curr->next == NULL) { //if the end of the list has been reached
                curr->next = &node;
                node.prev = curr;
                node.next = NULL;
            } else {              //insert the new DoctorNode in the middle:
                curr->next->prev = &node;
                node.next = curr->next;
                curr->next = &node;
                node.prev = curr;
            }
     }

列表中的每个节点都定义为一个结构:

    struct DoctorNode {
      Doctor value;
      DoctorNode *next;
      DoctorNode *prev;
    }

因此,一旦通过 hireDoctor 函数,如果我“雇用”了一位名叫 John Smith 的医生,我希望 drListHead 指向 John Smith,这似乎就是发生的事情。但是,在第二次通过该函数时,雇用 Jane Doe,似乎 drListHead 在进入该函数时已经指向 Jane Doe。我无法弄清楚它在哪里发生变化。任何想法将不胜感激!

最佳答案

问题在这里:

        if (drListHead == NULL) {    //if doctor list is empty,
            drListHead = &node;    //insert the node at the beginning  <------
            node.next = NULL;
            node.prev = NULL;
        } 

您的节点在堆栈上初始化,并且在退出 hireDoctor 后它将指向堆栈的地址。下次您调用 hireDoctor 时,节点再次指向同一个地址,即 Jane Doe(纯属巧合)。你需要这个:

            if (drListHead == NULL) {    //if doctor list is empty,
                drListHead = new DoctorNode();    //heap allocation 
                drListHead->next = NULL;
                drListHead->prev = NULL;
            }

但请记住,您必须释放未使用的内存。

关于c++ - 链表头指针在传递给函数 c++ 时发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12820069/

相关文章:

java - 当项目添加到java中的列表对象时自动运行线程

c++ - 函数指针作为模板参数,类型推导失败

c++ - Mingw32 是否支持 std::thread?

c++ - 比较 50 个以上字符串的有效方法

c - C 中的数组很麻烦

java - 链表从某个位置困惑中删除节点

c++ - C++标准兼容库容器的完整接口(interface)是什么?

c++ - 实现可以转换为 Stream<U> 的 Stream<T>,其中 U 是 T 的基数

c++ - 尝试通过共享指针使用变量时读取访问冲突

c - 反向链表