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)?
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() ).