c++ - 链表指针问题
问题描述
有 2 个 createList 函数,一个打印出链表的所有元素,而另一个没有,为什么会这样?
/*following createList prints out fine */
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else root->next = createList(root->next , a);
return root;
}
/*following createList prints out only 1st element, why?*/
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else createList(root->next , a);
return root;
}
void read(node* root){
if(root==NULL) return;
else{
cout << root->data << " ";
read(root->next);
}
}
解决方案
在这个函数中
/*following createList prints out only 1st element, why?*/
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else createList(root->next , a);
return root;
}
它的参数根是函数的局部变量,它保存传递给函数的参数值的副本。因此更改副本不会影响原始参数。
在这个函数中与上面的函数相反
/*following createList prints out fine */
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else root->next = createList(root->next , a);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return root;
}
原始参数与新值的分配。
为了更清楚,考虑一个非常简单的程序
#include <iostream>
int f( int x )
{
x *= 10;
return x;
}
int main()
{
int x = 10;
std::cout << "Before call of f: " << x << '\n';
f( x );
std::cout << "After call of f: " << x << '\n';
x = f( x );
std::cout << "After call of f: " << x << '\n';
return 0;
}
它的输出是
Before call of f: 10
After call of f: 10
After call of f: 100
在第一次调用该函数后,main 中f
的变量x
没有改变,因为该函数处理其参数的副本。
在第二次调用函数后,变量发生了x
变化,因为它被新值重新分配了。
推荐阅读
- loops - ReadString 读取 EOF 时如何中断循环?
- python - NLTK 不能在带有 KivyMD 的 Android Buildozer 应用程序中工作
- assembly - 具有两个大小为 10 的整数数组 X 和 Y 的汇编程序,其中 Y 包含:如果 X 中的元素为正,则为 1,如果该元素 < = 0,则为 0
- groovy - Groovy,检查数组中的所有元素是否包含子字符串
- python - 如果您之前没有连接到 wifi,如何通过 linux 或 Windows 上的 python 连接到 wifi。(输入:SSID、密码)
- docker-compose - 如何让 docker-compose 使用所选图像主要版本的最新次要版本?
- jquery - 根据窗口宽度添加/删除元素
- javascript - 如何制作这些斜线
- javascript - HTMLElement.focus() 在 HTMLElement.onpointerdown 中不起作用
- javascript - 如何组织具有维度的列表