https://leetcode-cn.com/problems/linked-list-cycle-ii/

快慢指针

  • 快指针一次走两步, 慢指针一次走一步
  • 第一次相遇时,快指针回到原点,慢指针不动,接下来快指针也变成每次走一步,然后继续, 再次相遇就是第一个入环的节点

    1. public ListNode detectCycle(ListNode head) {
    2. if (head == null || head.next == null || head.next.next == null) {
    3. return null;
    4. }
    5. ListNode slow = head.next;
    6. ListNode fast = slow.next;
    7. while (slow != fast) {
    8. if (fast.next == null || fast.next.next == null) {
    9. return null;
    10. }
    11. fast = fast.next.next;
    12. slow = slow.next;
    13. }
    14. fast = head;
    15. while (slow != fast ) {
    16. fast = fast.next;
    17. slow = slow.next;
    18. }
    19. return slow;
    20. }