gpt4 book ai didi

c++ - 链表 : Inserting from the Beginning

转载 作者:行者123 更新时间:2023-11-30 05:08:27 25 4
gpt4 key购买 nike

我有两种从头插入节点的方法。第一个有效,而第二个无效。你能解释一下为什么吗?

(列表已经有一些元素,head是那个列表的头节点)

我已经像这样初始化了 head

list *head = new list;

 void push(list **head, int info)
{
list *node=new list;
node->data=info;
node->next=*head;
*head=node;
}
push(&head,5);

下一个是

void push(list *head, int info)
{
list *node=new list;
node->data=info;
node->next=head;
head=node;
}
push(head,5);

最佳答案

第一个版本接收一个指向头指针的指针,而第二个版本接收一个头指针的拷贝。因此,第一个版本可以修改头指针,而第二个版本只能修改这里的本地拷贝:head = node

要使第二个版本工作,您可以通过引用接受 head 指针:只需将函数签名选择为 void push(list * & head, int info) (注意 &)

您可能想阅读有关 pointers 的更多信息和 references .

关于c++ - 链表 : Inserting from the Beginning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46845151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com