gpt4 book ai didi

java - 删除单链表的最后一个节点

转载 作者:行者123 更新时间:2023-11-29 04:12:32 26 4
gpt4 key购买 nike

下面是删除单链表最后一个节点的函数。我不明白,为什么我们要创建一个临时节点?我尝试在没有临时节点的情况下执行此操作并使用节点本身,但输出不会删除最后一个节点。另外,既然我们使用的是临时节点,为什么我们要返回节点而不是临时节点?我们没有对节点进行任何更改,那么节点会受到怎样的影响?

public Node deleteLastNode(Node node)
{
if (node.next == null || node == null)
return null;
Node temp = node;

while (temp.next.next != null)
{
temp = temp.next;
}
temp.next = null;
return node;
}

最佳答案

I don't understand why we are creating a temp Node?

那是因为您将当前迭代节点存储在 temp 变量中。

I tried doing it without the temp Node and used the node itself but the output doesn't delete the last node.

提供任何反馈所需的代码。

Also, since we are using the temp Node, why are we returning node and not temp?

因为您要返回对列表头部的引用,所以它不再有最后一个元素。

We aren't making any changes to node which so how is node getting affected?

你在这里删除最后一个节点temp.next = null;

希望它能让您清楚一些。

关于java - 删除单链表的最后一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186423/

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