Reputation: 568
Insert is a method which appends an item to the end of my linked list.
Can't figure out how to code for the case where Node is null, and I just want to add to it.
struct Node{
int data;
Node *next;
Node(int data):data(data),next(NULL){}
void insert(int data){
if (this==NULL){
this=new Node(data); // compiler is complaining here.
// how would I go about setting the value of this (which is presently NULL) to a new Node?
}
}
}
Upvotes: 0
Views: 64
Reputation: 6834
Something like this:
void insert(int data)
{
Node* newNode = new Node(data);
if (next!=NULL)
newNode->next = next;
next = newNode;
}
You cannot assign directly to 'this'; what you need to consider is how to represent an empty list, most likely by:
Node* head = 0;
So you add the first node by
head = new Node(data);
Upvotes: 1
Reputation: 1686
you can not assign a value to this pointer which is a special keyword and should always point to a valid block of memory. by looking at your usage, could you be trying to mean this:
void insert(int data){
if (!next){
next = new Node(data);
}
Upvotes: 3