c - 按升序插入节点

标签 c

我尝试将包含字符串的节点按升序插入到链表中。如果第一个元素的首字母高于字符串的其他首字母,则该方法有效。例如,

“泽内普”

“锡兰”

“德米尔”

这个方法效果很好。 但是,如果第一个字符串的首字母小于列表中任何字符串的首字母,则不会打印任何内容。

“阿里”

“泽内普”

“锡兰”

这会腐败。 我追踪了代码但找不到。

struct friendNode
{
    char firstName[30];
    char lastName[30];
    char gender[1];
    char birthYear[10];
    struct friendNode *next;
};

struct friendRecord
{
    struct friendNode *head;
    struct friendNode *tail;
    int size;
};
void insertFriend(struct friendNode *node, struct friendRecord *list)
{
    struct friendNode *temp_node;
    temp_node = list->head;

    if(temp_node->next == NULL)
    {
        temp_node->next = node;
        list->tail = node;
    }

    else
    {
        while(strcmp(node->firstName, temp_node->next->firstName) >= 0 )
            temp_node = temp_node->next;

        if(temp_node->next == NULL)
        {
            temp_node->next = node;
            list->tail = node;
            return;
        }

        node->next = temp_node->next;
        temp_node->next = node;
    }
}

最佳答案

插入链表是非常基本的事情。这是一种方法:

void insertFriend(struct friendNode *node, struct friendRecord *list)
{
    struct friendNode *pre = NULL;
    struct friendNode *post = list->head;

    while (post && strcmp(node->firstName, post->firstName) >= 0)
    {
        pre = post;
        post = post->next;
    }
    if (pre == NULL)
    {
        list->head = node;
    }
    else
    {
        pre->next = node;
    }
    node->next = post;
    if (post == NULL)
    {
        list->tail = node;
    }
}

关于c - 按升序插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208668/

相关文章:

c - MISRA 2012 规则 8.10 静态内联

c - 在 Linux 中使用什么函数来枚举目录的内容?

c - OpenMP 对数组中每个元素的缩减

c - "for(; ;)"优先于 "while(1)"

c - 头文件最有效的使用方法是什么

c - Linux:brk()错误 'Cannot allocate memory'

c - 如何在C中生成随机 float

c - 我正处于解决这个问题的边缘。看看...谁能告诉我我应该改变什么?

c - 无法访问结构数据

c - do-while 或 while 循环将继续接受用户的输入,但在我用 c 语言输入字符串 "exit"(不区分大小写)后将终止