if you think about the total distance of the fast pointer and the slow pointer, then solution should be very clear.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class Solution { public ListNode detectCycle(ListNode head) { if (head == null || head.next == null) return null; ListNode fast = head.next.next; ListNode slow = head.next; while (fast != null && slow != fast){ slow = slow.next; fast = fast.next == null?null:fast.next.next; } if (fast == null) return null; fast = head; while (fast != slow){ fast = fast.next; slow = slow.next; } return slow; } } |
No comments:
Post a Comment