有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

共 (4) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

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

    如果没有临时节点(又称光标或指针),您如何与列表中的任何节点进行交互

  3. # 3 楼答案

    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;

    希望它能让你明白一点

  4. # 4 楼答案

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

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

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