【问题标题】:Remove duplicate elements from a linked list从链表中删除重复元素
【发布时间】:2022-11-14 11:42:16
【问题描述】:

我试图阅读一个删除链表中重复元素的程序。我对 while 循环中的中断条件感到困惑。下面是代码。

public static <T> void removeDuplicates(SinglyLinkedList<T> list) {
        SinglyLinkedList<T>.Node current = list.headNode; // will be used for outer loop
        SinglyLinkedList<T>.Node compare = null;     // will be used for inner loop

        while (  current != null && current.nextNode != null) {
            compare = current;
            while (compare.nextNode != null) {
                if (current.data.equals(compare.nextNode.data)) { //check if duplicate
                    compare.nextNode = compare.nextNode.nextNode;
                } else {
                    compare = compare.nextNode;
                }
            }
            current = current.nextNode;
        }
    }

while ( current != null &amp;&amp; current.nextNode != null) 的声明让我感到困惑。如果我从语句中删除current != null,则输出相同。假设列表是 1 -> 2 -> 3 -> null。现在最初 current 是 1 ,然后如果我们遍历列表并且当 current 指向 3 时,那一刻(current.nextNode == null)并且如果我只使用 while( current.nextNode != null ,那对我来说就可以了。那为什么作者使用current != null。请帮助我消除混乱。

【问题讨论】:

  • 尝试将一个没有元素的列表传递给它,看看会发生什么。

标签: java data-structures java-8 linked-list


【解决方案1】:

一个完全空的列表将有currentnull。点是取消引用运算符 - 取消引用 null 会导致 NullPointerException。因此,使用空列表调用该方法会导致 NPE,而正确的操作是什么都不做(“从这个空列表中删除所有重复项”是一项可以完成的工作,它是通过什么都不做来完成的 - 没有在空列表中重复,因此无需删除)。

实际上,对于非空列表,while 子句的那一部分永远不会相关。鉴于它永远不会到达那里(列表中的最后一个节点由于有nullcurrent.nextNode 而已经使while 子句失败)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2015-01-05
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多