When passing the header of a linked list to a function. Why do we need to pass it by reference, for example, to push (node ​​* & head, int key)

The address of the head and head is printed: Head: 0x603050 & head: 0x7fffffffe4b8: what does this mean?

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;
    }    
}

The main function in which all other functions are called from the list of links - 8.4.2 main function

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;
}
+3
source share
3 answers

Why do we need to pass it by reference, for example, to push (node ​​* & head, int key)

Otherwise, the set value will not be set linkNodeas the current one 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()
    }

You have a link to a pointer ( head) that will be "returned" from the function push(), and set the pointer headpassed from the caller correctly:

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

delete node, new node();. , , .

+4

" "; .

, , head , , , .


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

, , .


reverse(head);          //this requires &head

head . , head .

return .

+3

, head push, , push head. , . , , head ( NULL), push, , head . , , NULL ( ).

Note that this may disappear if you create a linked list class instead of treating your nodes as linked lists themselves (i.e., encapsulating nodes in the list interface is what the standard library does).

+1
source

All Articles