如何在C中的链表中插入新项(在列表末尾)
我试图用C语言来理解链表,结果弄糊涂了 我的问题是:这是否正确地将不同的如何在C中的链表中插入新项(在列表末尾),c,pointers,struct,linked-list,C,Pointers,Struct,Linked List,我试图用C语言来理解链表,结果弄糊涂了 我的问题是:这是否正确地将不同的人员插入列表末尾?还是只是在开头插入它们? 目前,我正试图在我的链接列表末尾插入一个新的人。我的结构定义如下: struct person { char *name; int age; struct person *next; }; 我正在从预先分配的阵列访问数据: #define HOW_MANY 7 char *names[HOW_MANY]= {"Simon", "Suzie", "Al
人员插入列表末尾?还是只是在开头插入它们?
目前,我正试图在我的链接列表末尾插入一个新的人。我的结构定义如下:
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循环没有被执行,我不知道为什么。
谢谢 您确实将新记录放在了列表的开头。您必须意识到newPeople->next在新分配时始终为空。您需要遍历人员,直到“人员->下一步”为空,然后将其指定为“新人员”。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;
}
我投票结束这个问题,因为没有代码审查服务。如果您的代码有问题,请提供特定的问题描述,并发布一篇文章。在此之前,调试器将是您最好的朋友。不要将malloc
&friends的结果强制转换为C!如果在末尾添加,则newPeople->next
将始终为NULL
。要将newPeople
添加到列表中,您需要步行people
直到到达people->next==NULL
,在这种情况下,此people->next
应指向newPeople
。