来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii

描述

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明:不允许修改给定的链表。

进阶:
你是否可以使用 O(1) 空间解决此题?

题解

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode detectCycle(ListNode head) {
  14. ListNode fast = head, slow = head;
  15. while (fast != null && fast.next != null) {
  16. fast = fast.next.next;
  17. slow = slow.next;
  18. if (fast == slow) {
  19. break;
  20. }
  21. }
  22. if (fast == null || fast.next == null) {
  23. return null;
  24. }
  25. slow = head;
  26. while (fast != slow) {
  27. fast = fast.next;
  28. slow = slow.next;
  29. }
  30. return slow;
  31. }
  32. }

参考