为什么此功能无法成功将节点插入链表?

时间:2013-10-12 19:06:42

标签: c list pointers linked-list stack

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

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在此函数之外没有更改,但我不确定如何解决此问题。我需要一个指向指针的指针吗?

2 个答案:

答案 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);