Reputation: 1
int insert(node* head) {
if (head == NULL) {
node* temp = new node;
if (head == NULL) {
cout << "Error";
return 0;
}
temp->data = 20;
temp->next = NULL;
} else {
temp->next = insert(temp->next);
}
return (temp);
}
I am trying to add node recursively but I got the error temp was not declared
. I do not understand why I am getting this error. When I always define temp
like this node* temp = new node;
but now I got an error.
Upvotes: 0
Views: 46
Reputation: 56
There seems to be multiple issues with your code:
int insert(node* head) {
if (head == NULL) {
node* temp = new node; // Newly created node will not be used at all
if (head == NULL) { // as head is NULL it will return 0
cout << "Error";
return 0;
}
temp->data = 20; // Code unreachable
temp->next = NULL;
} else {
temp->next = insert(temp->next); // Here you will again get an error for temp not declared
}
return (temp);
}
Upvotes: 0
Reputation: 37202
Local variables are only visible inside the scope they're declared in, and you're declaring temp
inside your first if
statement. You need to move the definition outside the if
clause:
int insert(node* head)
{
node* temp=new node; // <- move to here
if(head==NULL)
{
...
}
else
{
...
}
return temp;
}
Upvotes: 1