因此,我尝试执行此功能,只要用户输入唯一的单位字母,即可将单位添加到链接列表中。我的代码可以编译。但在第一次运行后,它只说“单位字母已经存在”,即使它应该还不存在。有人可以告诉我我哪里出错了吗?任何帮助,将不胜感激!
void addU(NODE** head){
NODE *newNode, *temphead, *current;
int check = 0;
char ul, nl;
newNode = (NODE*)malloc(sizeof(NODE));
newNode->unit = malloc(sizeof(UNIT));
/*Get unit details*/
printf("\n\n\tUnit Letter: ");
scanf(" %c", &(newNode->unit->letter));
printf("\n\tMaximum number of occupants: ");
scanf("%d", &(newNode->unit->max));
/*Check if unit letter is unique*/
temphead = current = *head;
if (temphead!=NULL){
while (current!=NULL){
ul = tolower(current->unit->letter); //convert to small case for comparison
nl = tolower(newNode->unit->letter);
if (ul == nl){
check=1;
printf("\n\n\tInvalid: Unit letter already exists.\n");
break;
}else current = current->next;
}}
/*Add newNode to list if unit letter is unique*/
if (check==0){
if (*head==NULL){
newNode->next = NULL;
*head = newNode;
}else{
newNode->next = *head;
*head = newNode;
}
printf("\n\n\tUnit successfully added!\n");
}
free(newNode);
free(newNode->unit);
}
最佳答案
如果在列表中插入新节点,请不要立即销毁它。
关于C 中的字符比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099746/