link=*q"之间的区别-6ren"> link=*q"之间的区别-在学习链表编码的过程中,我遇到了这两个东西,无法理解它们之间的区别,让我感到困惑。我一直在学习的这本书在我们在链表末尾添加新节点的部分解释了“temp=*q”。 So, if the list is -6ren">
gpt4 book ai didi

c - "temp=*q"和 "temp->link=*q"之间的区别

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:18 25 4
gpt4 key购买 nike

在学习链表编码的过程中,我遇到了这两个东西,无法理解它们之间的区别,让我感到困惑。我一直在学习的这本书在我们在链表末尾添加新节点的部分解释了“temp=*q”。

So, if the list is not empty, i.e.the condition if(*q==NULL) fails, then the next part would execute. Now temp is made to point to the first node in the list through the statement

temp=*q;

Now using temp we have traversed though the entire linked list using the statememnts:

while (temp->link!=NULL)
temp=temp->link;

稍后在列表开头添加新节点的编码中,我看到:

Now we need to make the link part of the node point to the existing first node. This has been achieved through the statement

temp->link=*q;

现在的问题是我无法区分这两个代码。他们在这两种情况下不是扮演着同样的角色吗?值得一提的是,temp 是用于列表上所有更新工作的临时节点,*q 是起始节点。

最佳答案

第一个例子

在开始使用 temp 遍历第一个示例中的列表之前,您有如下内存布局:

three-node list

然后您创建一个局部变量,temp。假设最初它是空指针:

temp pointing to NULL

然后你设置temp等于*q:

temp=*q;

这使得你的内存布局看起来像这样:

temp pointing to first node

然后你执行这个循环:

while (temp->link!=NULL) temp=temp->link;

这一步 temp 沿着列表的节点,直到它指向最后一个节点。所以在我的示例图中(具有三个节点),temp 将首先移动到列表中的第二个节点:

temp pointing to second node

然后它将移动到列表中的第三个节点:

temp pointing to third node

循环在这里结束,因为现在 temp->linkNULL

应该清楚,第一个赋值(temp=*q)和循环中的赋值(temp=temp->link)都没有改变链表的结构。这些分配只是使 temp 指向列表中的不同节点。

第二个例子

在您的第二个示例中,您要在列表的前面添加一个新节点。因此,您将 temp 设置为指向一个新节点:

temp pointing to new, unlinked node

然后你执行这个你发现混淆的语句:

temp->link=*q;

这是执行该语句后的内存布局:

new node points to prior first node

应该很清楚,与第一个示例不同temp 在赋值之后指向与赋值之前相同的节点。

下一步(未在您的问题中显示)将使用以下语句更新 *q 以指向新节点:

*q = temp;

这会将内存布局更改为:

*q points to new node

现在你不再需要 temp 了。假设您将从具有 temp 的函数返回,它会消失,留下您的内存如下:

final, four-node list

关于c - "temp=*q"和 "temp->link=*q"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18724392/

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