mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
@ -189,33 +189,28 @@ Java:
|
|||||||
```java
|
```java
|
||||||
public class Solution {
|
public class Solution {
|
||||||
public ListNode detectCycle(ListNode head) {
|
public ListNode detectCycle(ListNode head) {
|
||||||
// 1.寻找相遇点
|
|
||||||
ListNode fast = head;
|
|
||||||
ListNode slow = head;
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
while (fast != null && fast.next != null) {
|
while (fast != null && fast.next != null) {
|
||||||
fast = fast.next.next;
|
|
||||||
slow = slow.next;
|
slow = slow.next;
|
||||||
if (fast != slow) {
|
fast = fast.next.next;
|
||||||
continue;
|
if (slow == fast) {// 有环
|
||||||
|
ListNode index1 = fast;
|
||||||
|
ListNode index2 = head;
|
||||||
|
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
|
||||||
|
while (index1 != index2) {
|
||||||
|
index1 = index1.next;
|
||||||
|
index2 = index2.next;
|
||||||
|
}
|
||||||
|
return index1;
|
||||||
}
|
}
|
||||||
ListNode meet = fast;
|
|
||||||
|
|
||||||
// 2.寻找入口点
|
|
||||||
slow = head;
|
|
||||||
while (slow != fast) {
|
|
||||||
slow = slow.next;
|
|
||||||
fast = fast.next;
|
|
||||||
}
|
|
||||||
|
|
||||||
return fast;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
Reference in New Issue
Block a user