返回头部如何给我链接列表中的结果

发布于 2025-02-04 09:32:29 字数 799 浏览 5 评论 0原文

在以下代码中,该方法返回了我的数组头,该数组的引用是LinkedList的头部,并带有删除的重复项。我无法考虑的是,当所有指针更改当前时,头部如何包含该参考。

    public static Node removeDuplicates(Node head)
{
    Node previous = null;
    Node current = head;

    // take an empty set to store linked list nodes for future reference
    Set<Integer> set = new HashSet<>();

    // do till the linked list is empty
    while (current != null)
    {
        // if the current node is seen before, ignore it
        if (set.contains(current.data)) {
            previous.next = current.next;
        }
        else {
            // insert the current node into the set and proceed to the next node
            set.add(current.data);
            previous = current;
        }
        current = previous.next;
    }

    return head;
}

In the following code, the method returns me the head of the array which is reference of the head of the linkedlist with removed duplicates. What I can't get mind around is how does the head contain that reference when all the pointer changes has been made on current.

    public static Node removeDuplicates(Node head)
{
    Node previous = null;
    Node current = head;

    // take an empty set to store linked list nodes for future reference
    Set<Integer> set = new HashSet<>();

    // do till the linked list is empty
    while (current != null)
    {
        // if the current node is seen before, ignore it
        if (set.contains(current.data)) {
            previous.next = current.next;
        }
        else {
            // insert the current node into the set and proceed to the next node
            set.add(current.data);
            previous = current;
        }
        current = previous.next;
    }

    return head;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅哥哥的热头脑 2025-02-11 09:32:29

考虑从head开始的链接列表

A -> B -> C -> D -> null

遍历列表,我们以该顺序获得a,b,c,d

当前b,然后删除下一个节点(即c),因此b.next = d。现在,列表开始

A -> B -> D -> null

遍历列表现在将打印a,b,d。更改是在b中进行的,但是由于a具有对b的引用,因此在b后进行的任何更改代码>将反映在a开始的遍历中。

Consider the linked list

A -> B -> C -> D -> null

Traversing the list, starting at head, we get A,B,C,D in that order.

Let current be B, and you remove the next node (ie. C), so B.next = D. The list now becomes

A -> B -> D -> null

Traversing the list would now print A,B,D. The change was made in B, but since the A holds a reference to B, any changes made in and after B would be reflected in the traversal starting at A.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文