我有一个带有患者列表的多层链接列表,每个患者列表都指向一个包含患者的链接列表,每个患者都指向一个医生的链接列表。我试图添加多个医生,但是当我尝试显示医生时,我得到一个无限循环,好像没有指向NULL的下一个指针一样。如果只有一位医生,那么一切都会很好。
我尝试了多种方法,例如将旧节点设置为临时指针,然后将新节点设置为指向临时指针。我的患者列表链接列表和患者链接列表工作100%。
struct doctor {
char name[MAX_NAME];
struct doctor *next;
};
void addDoctor(char* patientNameInput, char* doctorNameInput)
{
struct patientList* tempList = list; // work on a copy of 'list'
int i = 0;
struct doctor* newDoctorNode = NULL;
newDoctorNode = (struct doctor*) malloc(sizeof(struct doctor));
struct doctor* tmp = NULL;
while (tempList != NULL)
{
while (tempList->patient->name[i] == patientNameInput[i])
{
if (tempList->patient->name[i] == '\0')
{
tempList->patient->doctors = newDoctorNode;
newDoctorNode->next = NULL;
for (int i = 0; i < 30; i++)
tempList->patient->doctors->name[i] = doctorNameInput[i];
}
i++;
}
tempList = tempList->next;
}
}
该功能搜索患者姓名和相应的患者列表链接列表。找到后,它将为相应的患者添加医生节点。如果我包括旧的临时指针尝试并显示该函数,则将得到一个无限循环。我希望输出结果能够显示1位以上的医生,并且没有错误。
更改以下内容:
tempList->patient->doctors = newDoctorNode;
newDoctorNode->next = NULL;
至:
newDoctorNode->next = tempList->patient->doctors;
tempList->patient->doctors = newDoctorNode;
这会将新的医生节点添加到现有医生列表的前面。如果您想将其添加到末尾,则需要遍历列表以找到末尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句