所以我正在尝试执行此功能,只要用户输入一个唯一的单位字母,就会向链表添加一个单位。我的代码编译。但是在第一次运行之后,它只是说“单位信已经存在”,即使它应该还没有。有人可以告诉我哪里出错了?任何帮助,将不胜感激!
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);
}
答案 0 :(得分:-1)
如果在列表中插入新节点,则不要立即销毁它。