gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:30:36 30 4
gpt4 key购买 nike

<分区>

我的二年级编程课有一个问题,涉及创建一组双向链表来表示医院以及医院中的医生和患者。一家医院有一份医生名单,每个医生都有一份病人名单。我的问题是,当我调用“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。我无法弄清楚它在哪里发生变化。任何想法将不胜感激!

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com