gpt4 book ai didi

java - 反转链表后对指针的影响

转载 作者:行者123 更新时间:2023-12-01 19:36:21 24 4
gpt4 key购买 nike

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

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?反向方法对快指针做了什么?

最佳答案

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

关于java - 反转链表后对指针的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com