C++将链表传递给函数,并通过不同的方式对其进行更改
C++ pass linked list to the function and change it by different ways
我必须编写一个函数,该函数不仅适用于复制的实例,还适用于原始实例。以下是我尝试过的:
/* Want to change the real instance */
void fun1 (MyList *list)
{
list = list->next; // working with local copy
*&list = *&list->next; // changes the real instance, but it doesn't work..Why?
}
/* Want to change AS local copy */
void fun2 (MyList *&list)
{
list = list->next; // changes the real instance, works fine.
// ..And there I want to make some changes AS with local copy..How?
}
我希望你能理解我的意思有什么想法吗?
&list
为您提供局部变量的地址,即参数在堆栈上的位置,然后您再次尊重它。所以您仍在制作本地副本。
您需要通过将签名更改为来传递列表的地址
void fun1 (MyList **plist);
void fun1 (MyList *&plist);
以便能够修改列表本身。
*&list = *&list->next; // changes the real instance, but it doesn't work..Why?
它不起作用,因为它采用了传递给函数的参数的地址(即本地副本),然后取消引用该地址以引用本地副本。
您的第二个版本(传递对指针的引用)使获得本地副本变得容易:
auto local = list;
或:
MyList *local = list;
两者都会很好用。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 以递归方式从链表中删除节点
- 重载 == 以递归方式比较两个链表
- 以C++递归方式对链表中的元素求和
- 如果我们使用链表数组来实现哈希表,则可以以不需要遍历的方式实现"add"。这是真的还是假的?
- C++将链表传递给函数,并通过不同的方式对其进行更改
- 对链表进行迭代的不同方式
- 当条目以有序的方式添加时,二叉搜索树有效地充当链表
- 链表排序方式的不同之处