简单来说,找入口。
链表题目一般都是双指针做.
两次相遇,第一次相遇后fast指针重置为头结点,但是此轮每次走一步,第二次相遇点即入口
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while (true) {
if (fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
这篇博客探讨了一种解决链表中环形结构的算法。通过使用双指针,第一次相遇后快指针重置并每次移动一步,第二次相遇点即为环的入口。这种方法有效地找到了链表环的起始节点。
1749

被折叠的 条评论
为什么被折叠?



