java - 当您只能访问该节点时,如何删除链表中的节点

标签 java data-structures linked-list

我的理解是,为了删除单链表中的节点,我们需要访问当前节点和前一个节点。我有以下逻辑:

public SingleNode delete(int val) {

    SingleNode current = head;
    SingleNode prev = head;

    while(current.data != val) {

        if (current.next == null) {
            return null;
        } else {
            prev = current;
            current = current.next;
        }

    }

    if(current == head) {
        head = current.next;
    } else {
        prev.next = current.next;
    }

    return current;

}

当您只能访问当前节点时,如何更改代码以便可以删除链表中的节点?

最佳答案

How can I change the code so that I can delete a node in linked list when you are given access to only the current node?

对于单链表,您无法删除具有给定引用的节点,除非您有前一个节点,或者您可以访问列表的头部.

如果你有头,你可以在 O(N) 步内找到前一个节点。

有一种通过修改节点来删除节点的方法,该方法在大多数情况下都有效,但有多种边缘情况使其变得困难。 (如果您需要支持并发删除和迭代等,它肯定不起作用。)

关于java - 当您只能访问该节点时,如何删除链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455677/

相关文章:

java - 检查 JTextField 字符

Java 字数统计

java - 某些 JVM 是否会缓存常用库类的静态初始化结果

C - 主函数中的(节点)结构不工作(有意避免使用单链表实现)

C 通过引用删除链表?

java - 使用 MVC 进行桌面应用程序开发的推荐书籍

php - 在 PHP 中获取特定格式的数据以用于 Post 请求

c - 访问结构体中的结构体

algorithm - 使用 rand5() 计算 rand7()

vector - IDRIS向量与链表