File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ package LinkedList ;
2+
3+ public class LinkedListCycleII142 {
4+
5+ class ListNode {
6+ int val ;
7+ ListNode next ;
8+
9+ ListNode (int x ) {
10+ val = x ;
11+ next = null ;
12+ }
13+ }
14+
15+ public ListNode detectCycle (ListNode head ) {
16+
17+ if (head == null || head .next == null )
18+ return null ;
19+
20+ ListNode ptr1 = head ;
21+ ListNode ptr2 = detectCycle1 (head );
22+
23+ if (ptr2 == null )
24+ return null ;
25+
26+ while (ptr1 != ptr2 ) {
27+ ptr1 = ptr1 .next ;
28+ ptr2 = ptr2 .next ;
29+ }
30+
31+ return ptr1 == ptr2 ? ptr1 : null ;
32+ }
33+
34+ private static ListNode detectCycle1 (ListNode head ) {
35+ if (head == null || head .next == null )
36+ return null ;
37+
38+ ListNode slow = head , fast = head ;
39+
40+ while (fast != null && fast .next != null ) {
41+ slow = slow .next ;
42+ fast = fast .next .next ;
43+
44+ if (slow == fast ) {
45+ return fast ;
46+ }
47+ }
48+ return null ;
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments