【问题标题】:Inserting a node in ascending order按升序插入节点
【发布时间】:2017-11-09 18:01:58
【问题描述】:

我尝试将包含字符串的节点按升序插入到链表中。如果第一个元素的首字母高于字符串的其他首字母,它会起作用。例如,

“泽尼普”

“锡兰”

“德米尔”

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

“阿里”

“泽尼普”

“锡兰”

这会损坏。 我跟踪了代码但找不到。

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;
    }
}

【问题讨论】:

  • 显示结构体friendNode和结构体friendRecord声明。
  • 当列表为空时,list->head 是否会成为 NULL?因为在这种情况下,您似乎使用 if(temp_node->next == NULL) 取消引用空指针。也许你想要if(temp_node == NULL) { list->head = node; list->tail = node; }

标签: c


【解决方案1】:

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

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;
    }
}

【讨论】:

    【解决方案2】:
    void insertFriend(struct friendNode *node, struct friendRecord *list)
    {
        struct friendNode *temp_node;
        temp_node = list->head;
    
        if(strcmp(node->firstName, list->head->firstName) < 0)
        {
            node->next = list->head;
            list->head = node;
        }
    
        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;
        }
    }
    

    如果它将成为第一个元素,您忘记编写代码以将节点附加到列表的头部。我没有尝试过,因为我没有完整的代码。试用。如果还是不行,我请求评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2016-03-09
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多