链表找环的相关问题,Floyd判圈法 · Sitrone/LeetcodeInJava@ca2e351 · GitHub
Skip to content

Commit ca2e351

Browse files
committed
链表找环的相关问题,Floyd判圈法
1 parent a7f18bd commit ca2e351

3 files changed

Lines changed: 91 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 在Linded List Cycle I的基础上再求出环的起始节点
3+
*
4+
*
5+
*/
6+
/**
7+
* Definition for singly-linked list.
8+
* class ListNode {
9+
* int val;
10+
* ListNode next;
11+
* ListNode(int x) {
12+
* val = x;
13+
* next = null;
14+
* }
15+
* }
16+
*/
17+
public class Solution {
18+
public ListNode detectCycle(ListNode head) {
19+
if(head == null || head.next == null)
20+
return null;
21+
22+
ListNode slow = head;
23+
ListNode fast = head;
24+
do{
25+
if(fast == null || fast.next == null) return null;
26+
27+
slow = slow.next;
28+
fast = fast.next.next;
29+
}while(slow != fast);
30+
31+
ListNode start = head;
32+
while(slow != start){
33+
slow = slow.next;
34+
start = start.next;
35+
}
36+
return start;
37+
}
38+
}
Lines changed: 21 additions & 0 deletions

0 commit comments

Comments
 (0)