java - 无法将链接列表的最后位置设置为 NULL

标签 java data-structures linked-list

我编写了从链接列表中删除特定位置处的节点的代码。

static Node deletesNodebyposition(Node root,int position)
{
    if(root == null)
        return null;

    Node head = root;
    int x=1;
    while(x < position && root !=null){
        root = root.next;
        x++;
    }
    if(root.next !=null) {
        root.data = root.next.data;
        root.next = root.next.next;
    }
    else
        root = null;

    return head;
}

代码工作正常,直到我选择要删除的最后一个节点。当我输入删除节点的最后一个位置时,我试图将该节点设置为 NULL。但是当我从函数返回并打印结果列表时,我仍然找到最后一个 Node.js 文件。我无法理解为什么最后一个节点无法设置为 NULL。

最佳答案

假设有一个链表, 3->4->6->7->1 并且您必须删除最后一个位置(第5个位置)的数字,

“root”的类型是“Node”而不是 LinkedList。在您的代码中,当您到达最后一个位置时,变量“root”将保存存储数据“1”的位置的地址,例如,

根=@addrlocation

当你分配时,

根=空

“root”变量不指向任何内容,实际上您不会删除任何内容。这里的关键点是你必须将最后一个节点的“下一个”节点设置为“null”

在上面的链表中,最后一个保存数据“7”的节点仍将保存“下一个”节点的地址作为@addrlocation。因此,对于您提到的特定情况,链接列表不会因您的更改而产生任何影响。

您可以引用前一个节点“previous”来解决问题。我修改了您的代码并粘贴在下面,

static Node deletesNodebyposition(Node root,int position)
 {
        if(root == null)
            return null;

        Node head = root;
        Node previous = null;
        int x=1;
        while(x < position && root !=null){
            previous = root;
            root = root.next;
            x++;
        }
            previous.next = root.next;
        return head;
    }

关于java - 无法将链接列表的最后位置设置为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074048/

相关文章:

java - 如何在 JFreeChart 中自定义 CategoryPlot 项目的工具提示?

java - 如何将 webview 添加到具有更多小部件的布局

java - 在 Java8 中推断 Optional 的泛型

algorithm - 如何验证二叉搜索树?

algorithm - 如何在 O(n) 中找到数组中的前 m 个最小整数?

c++ - 是否有围绕 Win32 的无锁 SList 的合适的 C++ 包装器?

java - JPA复合键+序列

c - 关于 char 数组结构的问题

跨多个 SQL 服务器的 SQL 查询

c++ - 如何在两个 boost::intrusive::slist 对象之间传输节点