【问题标题】:Error when trying to sort linked list with string comparison尝试使用字符串比较对链表进行排序时出错
【发布时间】:2017-05-11 17:12:22
【问题描述】:

我必须用从文本文件中读取的一些数据构建一个链表,然后对其进行排序。 我的结构:

struct Person {
int age;
char *name;
struct Person *next;
};

typedef struct Person LIST;

从文件中读取:

while (fgets(line, sizeof(line), fp)) {
    LIST *node = (Person*)(malloc(sizeof(Person)));
    node->name = strdup(line);
    node->next = NULL;

    if (head == NULL) {
        current = head = node;
    }
    else {
        current = current->next = node;
    }
}
fclose(fp);

在此之后,我打印出看起来很好的链表。

理想情况下,我应该按年龄排序,但我没有成功将数据读入单独的变量。所以我尝试通过比较字符串来对列表进行排序。它说'nullptr',所以我在我的'if'语句中添加了另外两个条件((current->name[i]!=NULL)&&(current->name [i + 1]!= NULL)),但是得到了同样的错误。

for (int i = 0; i < 5; i++)
{
    if ( (current->name[i]!=NULL) && (current->name[i+1] != NULL) && ( (current->name[i]) > (current->name[i + 1]) ) )
    {

        char temp = NULL;
        current->name[i] = temp;
        current->name[i] = current->name[i + 1];
        current->name[i + 1] = temp;

    }
}

【问题讨论】:

  • 你正在排序你名字的字母
  • current-&gt;name 是一个字符数组。但current-&gt;name[i] 是char。
  • 以及为什么i &lt; 5。这是哪里来的?
  • 谢谢。我在文件中有 4 行。
  • 你把 name 的字符和链表的长度搞混了。

标签: c sorting data-structures linked-list


【解决方案1】:

您从未将年龄读入 Age 变量,因此您无法按年龄排序。如果你想按名称排序,你想使用strcmp(char *a, char *b)函数,它返回-1、0和1,取决于a b,所以你的条件应该变成:

if ((current != NULL) && (current->next != NULL) && strcmp(current->name, current->next.name) > 0)

这样你是在比较当前节点和下一个节点的实际名称,而不是比较同名的字母。

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多