题目

image.png

思路

  • 涉及环相关的都会考虑使用快慢指针来解决。
  • 通过快慢指针,如果它们相等,则说明存在环,出现null的,肯定不存在环。
  • 通常来说快指针都是慢指针的速度的两倍
  • 找到环起点如图所示

环链表的起点问题.svg

代码

  1. public ListNode detectCycle(ListNode head) {
  2. if (head == null || head.next == null) return null;
  3. ListNode slow = head.next, fast = head.next.next;
  4. while (fast != null && fast.next != null) {
  5. if (slow.equals(fast)) break;
  6. slow = slow.next;
  7. fast = fast.next.next;
  8. }
  9. if (fast == null || fast.next == null) return null;
  10. while (!head.equals(slow)) {
  11. head = head.next;
  12. slow = slow.next;
  13. }
  14. return slow;
  15. }

环形链表II