I have a problem for my 2nd year programming class that involves creating a set of doubly linked lists to represent a hospital, and the doctors and patients in the hospital. A hospital has a list of doctors, and each doctor has a list of patients. My issue is that when i call the “hireDoctor” function to add a doctor to the hospital’s list, somehow the head pointer is getting changed. here’s my code:
/* 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;
}
}
Each node in the list is defined as a struct:
struct DoctorNode {
Doctor value;
DoctorNode *next;
DoctorNode *prev;
}
So after once though the hireDoctor function, if i “hire” a doctor named John Smith, I’d expect drListHead to point to John Smith, which seems to be what happens. However, on the second time through the function, hiring Jane Doe, it seems that drListHead is already pointing to Jane Doe upon entering the function. I can’t figure out where it’s getting changed. Any thoughts would be greatly appreciated!
Problem is here:
Your node is initialized on the stack and after exit
hireDoctorit will point to stack’s address. Next time you callhireDoctornode again points on the same address which is Jane Doe(which is just a coincidence). You need this:But remember that you must implement freeing of unused to memory.