mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update 0142.环形链表II.md
添加 0142.环形链表II.md Java版本
This commit is contained in:
@ -186,6 +186,29 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
```java
|
||||
public class Solution {
|
||||
public ListNode detectCycle(ListNode head) {
|
||||
ListNode slow = head;
|
||||
ListNode fast = head;
|
||||
while (fast != null && fast.next != null) {
|
||||
slow = slow.next;
|
||||
fast = fast.next.next;
|
||||
if (slow == fast) {// 有环
|
||||
ListNode index1 = fast;
|
||||
ListNode index2 = head;
|
||||
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
|
||||
while (index1 != index2) {
|
||||
index1 = index1.next;
|
||||
index2 = index2.next;
|
||||
}
|
||||
return index1;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Python:
|
||||
|
Reference in New Issue
Block a user