【发布时间】:2017-05-19 08:16:07
【问题描述】:
您好,我正在编写一个管理学生列表的程序,我正在使用一个列表,每个元素的描述如下:
struct student
{
char lastname[50];
char name[50];
char date_of_birth[50];
char height[50];
struct student *next;
};
struct student *root=0; //this is the root node
这就是我向列表中添加元素的方式:
void add_element(struct student **root, char lastname[50], char name[50], char date_of_birth[50], char height[50])
{
if(*root == 0)
{
*root = malloc(sizeof(struct student));
strcpy((*root)->lastname,lastname);
strcpy( (*root)->name,name);
strcpy( (*root)->date_of_birth,date_of_birth);
strcpy( (*root)->height,height);
(*root)->next = 0;
}
else
{
add_element(&(*root)->next,lastname,name,date_of_birth,height);
}
}
我还写了 2 个函数,一个是读取文件,另一个是写入文件,文件包含所有学生,一切正常,但我需要一个函数按姓氏字母顺序对所有元素进行排序,我试着写了一个,但它不起作用,它一直在崩溃。
我尝试了很多东西都没有成功,这是一次尝试,但没有成功:-(
请帮帮我
void sort(struct student *head)
{
struct student **current;
struct student *tmp;
for(current = &head ; *current !=NULL ; current = (*current)->next)
{
if((*current)->next == NULL)
{
break;
}
switch(strcmp((*current)->lastname,(*current)->next->lastname))
{
case 0:
{
printf("user not valid");
break;
}
case 1:
{
tmp = *current;
*current = (*current)->next;
(*current)->next = tmp;
break;
}
}
}
}
【问题讨论】:
-
Hmmmm
char height[50];--> 50 意味着非常个高的学生的可能性。 ;-) -
什么是
struct alunno? IAC,推荐*root = malloc(sizeof(struct alunno));-->*root = malloc(sizeof *(*root));并发布 true 代码。 -
您是否注意到您收到的编译器警告?例如:
current = (*current)->next应该产生警告,因为current是student **而(*current)->next是student *。 -
注意:对于
N学生,要添加另一个add_element()的学生,该函数可能会递归N次。如果N很大,那么这肯定是非展开代码的问题。建议一个非递归的解决方案。 -
不要在开关中使用
strcmp的结果。结果保证为0,或任何负值或正值 - 不是具体的 1 或 -1。
标签: c list sorting alphabetical alphabetical-sort