/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if (head == null){ return null; } ListNode slow = head; ListNode fast = head; int count = 0; while(true){ if (fast.next == null || fast.next.next == null){ return null; } count++; slow = slow.next; fast = fast.next.next; if (slow == fast){ break; } } slow = head; fast = head; for (int i=0;i<count;i++){ fast = fast.next; } while(true){ if (slow == fast){ return slow; } slow = slow.next; fast = fast.next; } } }
Linked List Cycle II
最新推荐文章于 2022-12-06 22:57:02 发布