File tree 1 file changed +21
-15
lines changed
src/main/java/com/fishercoder/solutions 1 file changed +21
-15
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import com .fishercoder .common .classes .ListNode ;
4
4
5
- /**Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
5
+ /**
6
+ * 142. Linked List Cycle II
7
+
8
+ Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
6
9
7
10
Note: Do not modify the linked list.
8
11
9
12
Follow up:
10
- Can you solve it without using extra space?*/
13
+ Can you solve it without using extra space?
14
+ */
11
15
public class _142 {
12
16
17
+ public static class Solution1 {
13
18
public ListNode detectCycle (ListNode head ) {
14
- ListNode slow = head ;
15
- ListNode fast = head ;
16
- while (fast != null && fast .next != null ) {
19
+ ListNode slow = head ;
20
+ ListNode fast = head ;
21
+ while (fast != null && fast .next != null ) {
22
+ slow = slow .next ;
23
+ fast = fast .next .next ;
24
+ if (slow == fast ) {
25
+ ListNode slow2 = head ;
26
+ while (slow2 != slow ) {
17
27
slow = slow .next ;
18
- fast = fast .next .next ;
19
- if ( slow == fast ) {
20
- ListNode slow2 = head ;
21
- while (slow2 != slow ) {
22
- slow = slow .next ;
23
- slow2 = slow2 .next ;
24
- }
25
- return slow ;
26
- }
28
+ slow2 = slow2 .next ;
29
+ }
30
+ return slow ;
27
31
}
28
- return null ;
32
+ }
33
+ return null ;
29
34
}
35
+ }
30
36
}
You can’t perform that action at this time.
0 commit comments