繁体   English   中英

当将链表的头部传递给函数时,为什么我们需要通过引用传递它,例如在 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)

打印出head和&head的地址: head:0x603050 &head :0x7ffffffffe4b8: 什么意思?

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实例new node(); . 在您所展示的不同上下文中,这可能会导致内存泄漏。

那不是“参考参考”; 它是对指针的引用。

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


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

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


reverse(head);          //this requires &head

在这个调用之后, head现在指向列表的新头部。 如果您想通过这将是不可能的head按值。

另一种实现可能会return新的头指针,而不是使用这种“输出参数”约定。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM