我正试图了解C中的链接列表,并最终让自己感到困惑。
我的问题是:这是否正确地在列表末尾插入了不同的people
?或者只是在开头插入它们?
目前我正在尝试在链接列表的末尾插入新的person
。我的结构定义如下:
struct person {
char *name;
int age;
struct person *next;
};
我正在从预先分配的数组中访问数据:
#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};
这是我在结尾函数中的插入:
static struct person * insert_end(struct person *people, char *name, int age)
{
struct person *newPeople = (struct person*)malloc(sizeof(struct person));
if (newPeople == NULL)
{
perror("Memory allocation failed");
abort();
}
newPeople->name = name;
newPeople->age = age;
if (people == NULL)
{
newPeople->next = people;
people = newPeople;
return people;
}
else {
while(newPeople->next != NULL)
{
newPeople->next = people;
}
people = newPeople;
return people;
}
}
我认为函数中的while循环没有被执行,我无法弄清楚为什么。 谢谢!
答案 0 :(得分:2)
您确实将新记录放在列表的开头。您必须意识到newPeople-> next将始终为null,因为它是新分配的。你需要遍历人,直到people-> next为NULL然后asign newPeople。
答案 1 :(得分:0)
newPeople->next
在读取之前未给出值,从而导致未定义的行为。因此代码在最后或开始时都没有正确插入。
while(newPeople->next != NULL) // undefined behavior
以下不初始化newPeople
指向的对象。
struct person *newPeople = (struct person*)malloc(sizeof(struct person));
代码似乎是使用以下内容制作循环链接列表。
if (people == NULL) {
newPeople->next = people;
...
虽然没关系,但更常见的是形成NULL
已终止的列表,我认为这是您的目标。
static struct person * insert_end(struct person *people, char *name, int age) {
// struct person *newPeople = (struct person*)malloc(sizeof(struct person));
// No need for cast. Recommend sizeof object rather than sizeof type
struct person *newPeople = malloc(sizeof *newPeople);
if (newPeople == NULL) {
...
}
// Best to initial all fields.
newPeople->name = name;
newPeople->age = age;
newPeople->next = NULL;
if (people == NULL) {
return newPeople; // New head node
}
// else not needed
// else {
// Code was attempting to march down wrong list.
// Create `walker` instead.
struct person *walker = people;
while(walker->next != NULL) {
walker = walker->next;
}
walker->next = newPeople;
return people;
}