C++将链表传递给函数,并通过不同的方式对其进行更改

C++ pass linked list to the function and change it by different ways

本文关键字:方式 链表 函数 C++      更新时间:2023-10-16

我必须编写一个函数,该函数不仅适用于复制的实例,还适用于原始实例。以下是我尝试过的:

/* 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;

两者都会很好用。