C 中的字符比较

标签 c linked-list char

因此,我尝试执行此功能,只要用户输入唯一的单位字母,即可将单位添加到链接列表中。我的代码可以编译。但在第一次运行后,它只说“单位字母已经存在”,即使它应该还不存在。有人可以告诉我我哪里出错了吗?任何帮助,将不胜感激!

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/

相关文章:

java - 如何将随机数(0-10)分配给存储在链表中的字符串

java - Java中从BufferReader读取字符字段

c - Stream != nullptr Visual Studio,简单地打印 txt 文件中的值 (C)

c++ - 通过引用返回指针数组

c - 将 uint8_t 而不是 uint32_t 传递给函数(在 C 中)

c - 测试损坏的列表

与 C 相比的 Java 沙盒环境

c - INI 库 : linked list (abstract) issue

c - 数组输出错误

c - 在方法中传递字符数组作为参数,C 语言