mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-11-28 06:48:53 +00:00
添加py
This commit is contained in:
parent
4a4d5271e5
commit
2e9819611c
@ -10,7 +10,7 @@
|
||||
|
||||
#### 题目描述
|
||||
|
||||
> 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环
|
||||
> 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环。
|
||||
>
|
||||
> 如果链表中存在环,则返回 true 。 否则,返回 false 。
|
||||
|
||||
@ -28,7 +28,7 @@
|
||||
|
||||
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210321132015849.png)
|
||||
|
||||
好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。\
|
||||
好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。
|
||||
|
||||
**动画模拟**
|
||||
|
||||
@ -42,7 +42,6 @@ Java Code:
|
||||
```java
|
||||
public class Solution {
|
||||
public boolean hasCycle(ListNode head) {
|
||||
|
||||
ListNode fast = head;
|
||||
ListNode low = head;
|
||||
while (fast != null && fast.next != null) {
|
||||
@ -80,11 +79,11 @@ class Solution {
|
||||
public:
|
||||
bool hasCycle(ListNode *head) {
|
||||
ListNode * fast = head;
|
||||
ListNode * low = head;
|
||||
ListNode * slow = head;
|
||||
while (fast != nullptr && fast->next != nullptr) {
|
||||
fast = fast->next->next;
|
||||
low = low->next;
|
||||
if (fast == low) {
|
||||
slow = slow->next;
|
||||
if (fast == slow) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -93,3 +92,18 @@ public:
|
||||
};
|
||||
```
|
||||
|
||||
Python Code:
|
||||
|
||||
```py
|
||||
class Solution:
|
||||
def hasCycle(self, head: ListNode) -> bool:
|
||||
fast = head
|
||||
slow = head
|
||||
while fast and fast.next:
|
||||
fast = fast.next.next
|
||||
low = low.next
|
||||
if fast == low:
|
||||
return True
|
||||
return False
|
||||
```
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user