【发布时间】: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->name是一个字符数组。但current->name[i]是char。 -
以及为什么
i < 5。这是哪里来的? -
谢谢。我在文件中有 4 行。
-
你把 name 的字符和链表的长度搞混了。
标签: c sorting data-structures linked-list