将链表的头部传递给函数时。为什么我们需要通过引用来传递它,例如在 push(node* &head, int key)
when passing head of linked list to function.Why do we need to pass it by reference of reference such as in push(node* &head, int key)
打印出head和&head的地址:头:0x603050&头 :0x7fffffffe4b8:这是什么意思?
void push(node* &head,int key)// Inserts items at front of link list
{
node* linkNode=new node(); //declares new node
linkNode->data=key;
if(head==NULL) //if the link list is empty then create a new one.
{
linkNode->next=NULL;
head=linkNode; //1
}
else
{
linkNode->next=head;
head=linkNode;
}
}
从中调用所有其他函数的主函数链接列表为 8,4,2主要功能
int main(int argc, char** argv)
{
node* head=NULL; //initializing head to NULL
push(head,2); //creating link list
push(head,4); //this requires &head
push(head,8); //link list is 8,4,2
selectSort(head); //this does not require &head
reverse(head); //this requires &head
return 0;
}
为什么我们需要通过引用来传递它,例如在 push(node* &head, int key)
否则,将给定linkNode
设置为当前head
将不起作用:
if(head==NULL) //if the link list is empty then create a new one.
{
linkNode->next=NULL;
head=linkNode; // <- This statement changes the head variable passed from main()
}
您拥有的是对将从push()
函数"返回"的指针(head
)的引用,并正确设置从调用方传递的head
指针:
node* head=NULL;
push(head,2); // sets head to the node created for key '2'
不要忘记delete
您使用 new node();
创建的所有node
实例。在所示的不同上下文中,这可能会导致内存泄漏。
这不是"引用的引用";它是对指针的引用。
这意味着,一旦指针head
设置为指向函数中的新元素,此更改也会影响最初传递给函数的指针。
selectSort(head); //this does not require &head
实际上,如果函数对列表的所有元素执行排序,则可能应该这样做。
reverse(head); //this requires &head
在这次电话之后,head
现在指向名单的新负责人。如果按值传递head
,则无法执行此操作。
另一种实现可能会return
新的头指针,而不是使用此"out 参数"约定。
必须将head
传递给push
函数的原因是push
函数需要修改head
指针的值。 如果不通过引用传递它,则对它的任何更改都将仅在函数调用中可用。 例如,如果它不是通过引用传递的,并且您将head
(初始化为 NULL
)传递给 push
函数,则将创建一个新项,但 head
的值只会在函数内更新。 离开函数后,它仍将NULL
(因为您通过复制传递了指针)。
请注意,如果您创建一个链表类而不是将节点本身视为链表(即,将节点封装在列表接口下 - 这是标准库所做的),这可能会消失。
相关文章:
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用 Key 对 C++ 中的哈希映射进行排序. 无法排序
- std::<key-value>不同类型的对向量
- .value( "key" , default) 不适用于空的 json 对象吗?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- C++自己的对象堆栈.在 push() 上复制了什么?
- std::move(key) 同时迭代unordered_map<字符串,字符串>?
- C++ push() 和 pop() 方法使用指针的动态 LinkedList 的问题
- 如何像在javascript中一样"push" c ++映射
- cpp / c ++中的grpc客户端代码,元数据x-api-key/x-goog-api-key不起作用,给了我语音A
- 黄金描述的C++ "Key Function"是什么?
- 从更新查询获取'Cannot insert duplicate key'
- 如何计算C++中非重复值的数量 std::map<Key,Values>
- SWIG:包装 std::map<key 时编译器错误,val *>
- 模板堆栈类的复制构造函数中的 pop() 和 push() 不起作用
- getch() 函数在输入 key 时不执行任何操作
- 最适合"set with class member as key"的数据结构?
- 将"Enter Key"值分配给字符串 [C++]
- 这里不允许函数定义:void encryption(ifstream encrypt_file,ofstream key
- 将链表的头部传递给函数时。为什么我们需要通过引用来传递它,例如在 push(node* &head, int key)