Issue with List structure

I just started to learn about Linked list and came across the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Class IntNode
{
    public:
      ...
    private:
      int Data;
      IntNode* link;
};

typedef IntNode* IntNodePtr;

//To add a node at the head of a linked list:

void headInsert(IntNodePtr& head, int theData)
{
    head = new IntNode(theData,head);
}

//To add a node in the middle of a linked list:

void insert(IntNodePtr afterMe, int theData)
{
    afterMe -> setlink( new IntNode (theData, afterMe->getLink());
}


why is the head parameter in headInsert a call by reference parameter(IntNodePtr& head), while the afterMe in insert function a call by value parameter(IntNodePtr afterMe)?

Can't both be call by value parameters?

Thanks a lot!
Last edited on
Does anyone know what the difference is ? Thanks:)
I think you need to show the construction function code
closed account (D80DSL3A)
Can't both be call by value parameters?


No. head needs to be passed by reference to the headInsert() for the same reason that any variable is passed by reference - so the value of the variable can be changed by the function.
In this case, the location in memory pointed to by head (value of head) is changed by the assignment to new.

It's OK for afterMe to be passed by value to the insert() because what afterMe points to is not to be changed. A value that it points to is to be changed (through the call to the setLink() ).
Thanks fun 2 code!
Finally I understand why a pointer needs to be passed by reference as well:)
Topic archived. No new replies allowed.