简体   繁体   中英

Linked list,Confused about Function that adds node to head of the list

I have a question about a function that adds a creates/adds a new node to the top of the list. Here is the set up.

A head is created in the main program. We set the list to Null

IntNode* head = new IntNode(3,NULL);

My question is about the function that adds a node to the top of the list. Assumes that there is at least one node in the list.(the one we just created)

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

I know it creates a new node and makes the pointer already declared in the main program, which is passed, point to the new node. However I am confused about he "head" part on the parameter in the constructor(not the headInsert function). I am confused about what exactly is being passed when we pass head in the IntNode constructor above. That head sets the variable link, to point to what head is pointing to correct? ******My question is, Does it first set *link(the class variable) to point to what head is pointing to, in this case the node with the number 3 whose list points to NULL, AND THEN makes head point to the new NODE? So in other words the right part of the assignment is done first? I'm just very confused as to what is being passed in when we create the new node.

class IntNode
{
    public:
    IntNode( ) {}
    IntNode( int theData, IntNode* theLink)
    : data(theData), link(theLink) {}
    IntNode* getLink( ) const { return link; }
    int getData( ) const { return data; }
    void setData( int theData) { data = theData; }
    void setLink(IntNode* pointer) { link = pointer; }
    private:
    int data;
    IntNode *link;
    };




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

The evaluation of the sides of the assignment -

head

and

new IntNode(theData, head)

is not ordered at all, but prior to performing the assignment, both sides have been evaluated completely. Since neither side modifies the value of head , the results are the same regardless of the order of evaluation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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