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