将链表的头部传递给函数时。为什么我们需要通过引用来传递它,例如在 push(node* &head, int key)

when passing head of linked list to function.Why do we need to pass it by reference of reference such as in push(node* &head, int key)

本文关键字:push key int head node 函数 头部 链表 为什么 我们 引用      更新时间:2023-10-16

打印出head和&head的地址:头:0x603050&头 :0x7fffffffe4b8:这是什么意思?

void push(node* &head,int key)// Inserts items at front of link list
{
    node* linkNode=new node(); //declares new node
    linkNode->data=key;
    if(head==NULL)             //if the link list is empty then create a new one.
    {
        linkNode->next=NULL;
        head=linkNode;   //1
    }
    else
    {
        linkNode->next=head;
        head=linkNode;
    }    
}

从中调用所有其他函数的主函数链接列表为 8,4,2主要功能

int main(int argc, char** argv) 
{
    node* head=NULL;         //initializing head to NULL
    push(head,2);           //creating link list
    push(head,4);           //this requires &head
    push(head,8);           //link list is 8,4,2
    selectSort(head);        //this does not require &head
    reverse(head);          //this requires &head
    return 0;
}

为什么我们需要通过引用来传递它,例如在 push(node* &head, int key)

否则,将给定linkNode设置为当前head将不起作用:

    if(head==NULL)             //if the link list is empty then create a new one.
    {
        linkNode->next=NULL;
        head=linkNode; // <- This statement changes the head variable passed from main()
    }

您拥有的是对将从push()函数"返回"的指针(head)的引用,并正确设置从调用方传递的head指针:

node* head=NULL;
push(head,2); // sets head to the node created for key '2'

不要忘记delete您使用 new node(); 创建的所有node实例。在所示的不同上下文中,这可能会导致内存泄漏。

这不是"引用的引用";它是对指针的引用。

这意味着,一旦指针head设置为指向函数中的新元素,此更改也会影响最初传递给函数的指针


selectSort(head);        //this does not require &head

实际上,如果函数对列表的所有元素执行排序,则可能应该这样做。


reverse(head);          //this requires &head

在这次电话之后,head现在指向名单的新负责人。如果按值传递head,则无法执行此操作。

另一种实现可能会return新的头指针,而不是使用此"out 参数"约定。

必须将head传递给push函数的原因是push函数需要修改head指针的值。 如果不通过引用传递它,则对它的任何更改都将仅在函数调用中可用。 例如,如果它不是通过引用传递的,并且您将head(初始化为 NULL)传递给 push 函数,则将创建一个新项,但 head 的值只会在函数内更新。 离开函数后,它仍将NULL(因为您通过复制传递了指针)。

请注意,如果您创建一个链表类而不是将节点本身视为链表(即,将节点封装在列表接口下 - 这是标准库所做的),这可能会消失。