class Node{
public:
int data;
Node* next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
int main()
{
Node* node1 = new Node(12);
cout<< node1->data ;
return 0;
}
Can't understand that why are we creating pointer object for the node (Node* node1)?
Thanks for clearing my doubt in advance
CodePudding user response:
The code in main()
needs a pointer simply because that is what new
returns. The code is creating the Node
object in dynamic memory on the heap (and consequently leaking it, since there is no delete node1;
statement before the return
statement).
You could instead create the object in automatic memory on the stack, and thus not need a pointer, eg:
int main()
{
Node node1(12);
cout << node1.data;
return 0;
}
Typically, linked lists are created using dynamic memory so that new nodes can be added to the list dynamically, such as in a loop, or in response to user input, etc.