【发布时间】:2019-07-31 13:37:45
【问题描述】:
在以下带有字符串链接列表的代码中,我创建了 2 个指针,fast 和 slow。我将快指针移到末尾,将慢指针移到中间。然后我反转了右半边。
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,我不明白为什么。为什么它无法访问8 和5? reverse 方法对快速指针做了什么?
【问题讨论】:
-
您是否已经通过调试器运行了代码?
-
是的很多次@Thomas
-
一个问题是直接在
slow前面的节点的值仍然会引用它原来的“next”,即即使你从reverse()返回5,2仍然会引用4 .因此,您需要跟踪slow - 1并在reverse()之后设置其“下一个”,或者使其成为双向链表并相应地设置“上一个”引用。
标签: java linked-list singly-linked-list