在下面的程序中,我尝试按升序对人员列表进行排序。但是,我遇到了分段错误,我不知道如何更改程序以获得预期的结果。有什么建议吗?
#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
typedef struct person
{
char *name;
int age;
struct person *next;
}Person;
static int compare_people(Person *p1, Person *p2)
{
return strcmp(p1->name, p2->name);
}
static Person* insert_sorted(Person *headp, char *name, int age)
{
Person *p = malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
if (headp == NULL)
{
headp = p;
return p;
}
else
{
Person *current = headp;
Person *temp =NULL;
while(current != NULL && compare_people(current, p) < 0)
{
temp = current;
if(compare_people(current,p) > 0)
break;
current = current->next;
}
p->next = current;
temp->next = p;
return headp;
}
}
int main(int argc, char **argv)
{
Person *people2 = NULL;
for (int i = 0; i < 7; i++)
{
people2 = insert_sorted(people2, names[i], ages[i]);
//printf ("name: %s, age: %i\n", people2->name, people2->age);
}
while(people2 != NULL)
{
printf ("name: %s, age: %i\n", people2->name, people2->age);
people2 = people2->next;
}
return 0;
}
答案 0 :(得分:0)
对于初学者,最好按以下方式定义函数compare_people
static int compare_people( Person *p1, Person *p2 )
{
return strcmp( p1->name, p2->name ) < 0;
}
至于insert_sorted
那么循环中的条件
while(current != NULL && compare_people(current, p) < 0)
{
temp = current;
if(compare_people(current,p) > 0)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
break;
current = current->next;
}
没有意义,因为如果条件为真,那么while循环的当前迭代最初将不会被执行,因为循环的条件是
compare_people(current, p) < 0
这些条件相互矛盾。
当节点被添加到空列表时,您忘记将数据成员next
设置为NULL。
使用您的方法可以按以下方式编写函数
static int compare_people( Person *p1, Person *p2 )
{
return strcmp( p1->name, p2->name ) < 0;
}
static Person* insert_sorted( Person *headp, char *name, int age)
{
Person *p = malloc( sizeof( Person ) );
if ( p == NULL ) abort();
p->name = name;
p->age = age;
if ( headp == NULL || compare_people( p, headp ) )
{
p->next = headp;
headp = p;
}
else
{
Person *current = headp;
while ( current->next != NULL && !compare_people( p, current->next ) )
{
current = current->next;
}
p->next = current->next;
current->next = p;
}
return headp;
}
答案 1 :(得分:0)
(1)需要#include <string.h>
(2)您忘记初始化成员的next
。
p->name = name;
p->age = age;
p->next = NULL;//<--this
if (headp == NULL)
{
headp = p;
return p;
}
(3)temp
NULL
更改
p->next = current;
temp->next = p;
到
p->next = current;
if(temp)
temp->next = p;
else
headp = p;