I would like to understand why the new line help the program give different addresses

  Kiến thức lập trình

I am new to C++. I was trying to do a linked list in it; however, when I create with the method “add” a third node, the address was the same than the second one. This is the code:

`class linkedList{
public:

    struct Node{
        int value;
        Node * next;
    };

    Node * Phead = nullptr;
    Node * Ptail = nullptr;
    int count = 0;

void add(int value){ 
     Node n;
    if(Phead == nullptr){ 
        n.next = nullptr;
        n.value=value;
        Phead = &n;
        Ptail = &n;
    }

    else if(Ptail != nullptr){ 
        n.value = value;
        Ptail->next = &n; 
        n.next = NULL;
        Ptail = n; 
    }
        count++;    
}`

After watching a video I “understan” what I need to do; neverthless, I do not understand the logic behind it. This is the code:

`class linkedList{
public:

    struct Node{
        int value;
        Node * next;
    };

    Node * Phead = nullptr;
    Node * Ptail = nullptr;
    //dynamic memory. LINE ADDED
    Node * n;
    int count = 0;

void add(int value){ 
     n = new Node;
    if(Phead == nullptr){ 
        n->next = NULL;
        n->value=value;
        Phead = n;
        Ptail = n;
    }

    else if(Ptail != nullptr){ 
        n->value = value;
        Ptail->next = n; 
        n->next = NULL;
        Ptail = n; 
    }
        count++;    
}`

I would like to know what that pointer do.

I just want to understand the concept behind it.

New contributor

Ωmega is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT