【发布时间】:2012-10-10 13:06:28
【问题描述】:
我在第二年的编程课上遇到了一个问题,涉及创建一组双向链接列表来代表医院以及医院中的医生和患者。医院有医生名单,每个医生都有病人名单。我的问题是,当我调用“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。我无法弄清楚它在哪里发生了变化。任何想法将不胜感激!
【问题讨论】:
-
如果您在任何其他文档之后雇用 Doc Zygmunt Zyzz,您的
while循环取消引用NULL。 -
drListHead是在哪里定义的?您的问题很可能不在显示的代码中,因为您在调用drListHead时说已经设置...所以请显示Hospital的声明和对hireDoctor的调用 - 我也强烈建议实施在名为DoublyLinkedList或类似的类中的双向链表,而不是在名为Hospital的类中! -
你的
curr->value.getLast()应该是(curr->value).getLast() -
同意如果在你热这个函数之前你的头指针被改变了,那可能是因为其他一些函数运行不好并且改变它 - 你在这里发布的代码似乎对我有用。
标签: c++ pointers linked-list