Skip to content

Commit 99cec1c

Browse files
author
suke
committed
141
1 parent f7deb23 commit 99cec1c

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public ListNode detectCycle(ListNode head) {
14+
ListNode fast = head;
15+
ListNode slow = head;
16+
ListNode meet = null;
17+
18+
while(fast != null){
19+
fast = fast.next;
20+
slow = slow.next;
21+
if(fast == null){
22+
return null;
23+
}
24+
25+
fast = fast.next;
26+
if(fast == slow){
27+
meet = fast;
28+
break;
29+
}
30+
}
31+
while(meet != null && head != null){
32+
if(meet == head){
33+
return meet;
34+
}
35+
meet = meet.next;
36+
head = head.next;
37+
}
38+
return null;
39+
40+
41+
}
42+
}

0 commit comments

Comments
 (0)