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);
}
我正在尝试递归添加节点,但错误temp was not declared
.我不明白为什么会出现此错误。当我总是这样定义temp
时node* temp = new node;
但现在我遇到了错误。
变量仅在声明它们的作用域内可见,并且您在第一个if
语句中声明temp
。您需要将定义移到 if
子句之外:
int insert(node* head)
{
node* temp=new node; // <- move to here
if(head==NULL)
{
...
}
else
{
...
}
return temp;
}
您的代码似乎存在多个问题:
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);
}