【问题标题】:Effect to pointers after reversing a Linked List反转链表后对指针的影响
【发布时间】:2019-07-31 13:37:45
【问题描述】:

在以下带有字符串链接列表的代码中,我创建了 2 个指针,fastslow。我将快指针移到末尾,将慢指针移到中间。然后我反转了右半边。

public void test(ListNode head) {
    ListNode fast = head, slow = head;
    while (fast != null && fast.next != null) {
        fast = fast.next.next;  //to the end of the list
        slow = slow.next;   //to the middle
    }
    slow = reverse(slow);  
    fast = head;   
    while (fast != null) {
        System.out.println(fast.val); //fast pointer only goes until the middle of the list
        fast=fast.next;
    }
    return true;
}
public ListNode reverse(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

我不明白的是,一旦我反转了右半部分,快速指针只能访问直到 LinkedList 中间的元素。

例如,假设 LinkedList 有1->2->4->8->5。在 reverse(slow) 之后,slow 指针指向5->8->4,这很好。但是,现在快速指针指向1->2->4,我不明白为什么。为什么它无法访问85? reverse 方法对快速指针做了什么?

【问题讨论】:

  • 您是否已经通过调试器运行了代码?
  • 是的很多次@Thomas
  • 一个问题是直接在slow前面的节点的值仍然会引用它原来的“next”,即即使你从reverse()返回5,2仍然会引用4 .因此,您需要跟踪 slow - 1 并在 reverse() 之后设置其“下一个”,或者使其成为双向链表并相应地设置“上一个”引用。

标签: java linked-list singly-linked-list


【解决方案1】:

您的最终链接列表是1->2->4<-8<-54->(null)。您应该将 2 中的下一个设置为 2->5 某处可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2018-06-23
    相关资源
    最近更新 更多