0

该函数应该将节点插入到链表中,但它有一个错误并且插入的节点不会显示在链表中。错误在哪里?

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在这个函数之外没有改变,但我不知道如何解决这个问题。我需要指向指针或其他东西的指针吗?

4

2 回答 2

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似乎有点没用。

于 2013-10-12T19:13:16.160 回答
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);
于 2013-10-12T19:10:27.777 回答