【问题标题】:linked list add node using push function链表使用推送功能添加节点
【发布时间】:2017-10-07 06:21:50
【问题描述】:
struct node* AppendNode(struct node** headRef, int num) {
    struct node* current = *headRef;
    // special case for the empty list
    if (current == NULL) {
        Push(headRef, num);   ->why not use & in front of headref?
    } else {
        // Locate the last node
        while (current->next != NULL) {
            current = current->next;
        }
        // Build the node after the last node
        Push(&(current->next), num);
    }
}


void Push(struct node** headRef, int data) {
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
}

这是使用push添加节点的代码,但我在这部分感到困惑,Push(headRef, num);

,在这里为什么不使用&符号作为headref?如果参数只是headref,是否只复制指向push函数的指针?

headref 是一个指向节点的指针,如果我用参数headref 调用push,它只是将headref 复制到函数而不修改原始headref 吗?我在这里不太确定,所以headref-> head- >node(NULL),当前指向node(NULL),然后尝试在headref之后push num?

【问题讨论】:

  • 由于添加了Push,你可以看到两个函数的第一个参数struct node** headRef相同,所以你只需传递headRef。在第二种情况下,current->next 是一个指针,所以 &(current->next) 是所需的指针。
  • @weathervane *headref 指的是指向节点的指针,对吗?当我使用 &(current->next) 和 headref 调用 push 时有什么不同?为什么 headref 是一个地址? headref 是指向那个指向节点的指针吗?如果我只用headref作为参数调用push,它只是复制指针吗?

标签: c pointers data-structures linked-list push


【解决方案1】:

headref 是指向节点指针的指针,如果我用 push 调用 参数headref,是否仅将headref复制到函数而不是 修改源头文件?

要记住的一个方便的事情是:如果你想改变一个对象,你必须传入那个对象的地址

虽然您没有显示整个程序,但假设您在调用AppendNode 时传入指向headRef 的指针的地址是安全的(我认为)。正是这个地址传递给Push,以便Push 可以取消引用它一次并跳转到指向headRef 的实际指针并在那里写一些东西。

如果您将AppendNode 声明为AppendNode(struct node* headRef, int num),那么您会将&headRef 传递给Push

【讨论】:

  • 所以实际上当我调用推送函数时,我传递了一个指向节点指针的指针?并且 push 函数本身将参数指针指向节点的指针,所以它匹配吗?但我不太确定 push(headref, num) 在这里做什么,如果我在调用 push 后没有错,它将生成列表:headref -> head-> new node-> null 并且当前指向 null
  • @fiksx 内存中的每个位置都有两个属性(如果我可以这么说的话)地址和值。当您执行push(headRef, num) 时,您传递一个数字作为第一个参数。这个数字对你意味着什么?它是包含一个值的位置的地址(这个值是一个指针(地址),比如说v 指向结构)。在Push 函数中,您正在更改v 本身。希望有帮助。您会注意到您总是将NULL 传递给Push,以便Push 可以记下它使用malloc 生成的一些地址。
  • 谢谢!所以当我传递 headref 时,我传递 &head 是相同的,它是指向节点的指针的地址?还有pass NULL 和free 一样吗?什么时候需要释放 malloc 内存?
  • @fiksx 如果head 定义为struct node *head,则等于传递&head。要释放malloced 内存,请将malloc 返回的指针传递给free。检查这个:linux.die.net/man/3/free.
  • 哦,好的,非常感谢,而且是免费的,我可以在 main 中释放内存吗?例如,在调用函数和函数将结构返回到 main 之后,我可以释放 main 中的 malloc 内存吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2017-05-09
  • 2021-03-30
  • 2017-04-12
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多