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

Deleting the last node of a singly linkedlist

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

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;
}

通常使用temp节点的原因是node是列表的head/starting,这是我们拥有的列表的唯一表示(根据定义链表)。因此我们不想改变头部(或我们列表的表示),这就是从方法返回 node 的原因 - 这意味着我们在执行删除后返回更新的列表。

首先你需要把它切换到这样的条件

if (node.next == null || node == null) to 
if (node == null || node.next == null) 

这可能会导致空指针异常。 接下来..我认为temp需要在分配null之前保存数据,这样真正的引用就不会丢失数据。

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;

希望它能让你明白一些。

要将链表导航到它的最后一个节点,您需要一个指针(光标)指向您认为是最后等待测试的节点 this.next == null

如果没有临时节点(a.k.a 游标或指针),您如何与列表中的任何节点交互?