I've been trying to create a linked list in C++. I am trying to avoid using the keyword new
when creating it, but it doesn't seem to work
// Linked lists
struct Node
{
int value;
Node *next;
Node( int val ) : value( val ), next(nullptr) {};
};
int main()
{
vector<int> vec = { 2,5,7,1,4,7 };
//insertian
Node head(0); // we need to use a pointer
Node* ptr = &head;
for ( auto v : vec)
{
Node* temp = new Node( v ); // Node temp( v );
ptr->next = temp; //ptr->next = &temp;
ptr = ptr->next;
}
}
The code above works fine. But if I replace the code inside the loop with the commented lines, then it fails. I'm not sure why.
I was also informed that you need to perform a delete
when using new
. If using new cant be avoided then how can the delete
be performed?