【发布时间】:2020-04-15 04:01:05
【问题描述】:
我正在尝试在列表末尾插入一个新节点。我知道第一种方法是“正确的方法”。 但是我正在尝试使用另一个函数(第二个函数)的另一种方法,但我的列表似乎没有变化,有什么想法吗?
typedef struct listnode *listptr;
struct listnode {
int value;
listptr next;
};
void insert_at_end(listptr *x, int n) {
while ((*x) != NULL) {
x = &((*x)->next);
}
*x = (listptr)malloc(sizeof(struct listnode));
(*x)->next = NULL;
(*x)->value = n;
}
void insert_at_end_2(listptr x, int n) {
listptr newnode = (struct listnode *)malloc(sizeof(struct listnode));
newnode->next = NULL;
newnode->value = n;
while (x != NULL) {
x = x->next;
}
x = newnode;
}
【问题讨论】:
-
x是一个局部变量。更改它对调用者的变量没有影响。 -
仅供参考,
insert_at_end_2、malloc(sizeof(listptr))是错误的。它应该是malloc(sizeof *x)或malloc(sizeof(struct listnode))。孩子们,这就是为什么在 typedef 别名中隐藏指针类型是一个糟糕的主意。或许,该函数实际上 return 是什么?你忽略了那条相当重要的信息。无关,don't cast malloc in C progams -
我编辑了你注意到的原始代码就像你说的那样
-
@averageJoe 太好了,现在看看 Kaylums cmets。这是第一版和第二版的区别。
标签: c list struct linked-list