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