该函数应该将一个节点插入到链表中,但它有一个错误,并且插入的节点不会显示在链表中。错误在哪里?
int insert(struct Node *headList, int payload) {
struct Node *newNode;
newNode = malloc(sizeof(struct Node));
assert (newNode != NULL);
newNode->payload = payload;
newNode->next = headList;
headList = newNode;
return 0;
}
我很确定Node *headList
是按值传递的,因为headList
在此函数之外没有更改,但我不确定如何解决此问题。我需要一个指向指针的指针吗?
答案 0 :(得分:2)
此函数修改此指针指向的struct Node
:
int insert(struct Node *headList, int payload) {
...
headList = newNode;
...
}
然而,为了修改指针本身,你需要传递一个指针地址来初始化指针指针:
int insert(struct Node **headList, int payload) {
...
*headList = newNode; // <-- modifies the pointer itself
...
}
或者您可以使用返回值处理此问题,因为return 0
似乎有点无用。
答案 1 :(得分:1)
我没有看到return
语句的使用,所以不是使用指向指针的指针,而是将更新的headList
指针返回给调用者
struct Node * insert(struct Node *headList, int payload) {
struct Node *newNode;
newNode = malloc(sizeof(struct Node));
assert(newNode != NULL);
newNode->payload = payload;
newNode->next = headList;
headList = newNode;
return headList;
}
//in caller function
//Some code
headList = insert(headList,100);
如果您对return
语句非常具体,请使用指针指针
int insert(struct Node **headList, int payload) {
struct Node *newNode;
newNode = malloc(sizeof(struct Node));
assert (newNode != NULL);
newNode->payload = payload;
newNode->next = headList;
*headList = newNode;
return 0;
}
//in caller function
//Some code
status = insert(&headList,100);