This commit is contained in:
jaredliw 2021-07-13 21:06:03 +08:00
parent 4a4d5271e5
commit 2e9819611c

View File

@ -10,7 +10,7 @@
#### 题目描述 #### 题目描述
> 给定一个链表判断链表中是否有环pos代表环的入口若为-1则代表无环 > 给定一个链表判断链表中是否有环pos代表环的入口若为-1则代表无环
> >
> 如果链表中存在环则返回 true 否则返回 false > 如果链表中存在环则返回 true 否则返回 false
@ -28,7 +28,7 @@
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210321132015849.png) ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210321132015849.png)
好啦做题思路已经有了让我们一起看一下代码的执行过程吧\ 好啦做题思路已经有了让我们一起看一下代码的执行过程吧
**动画模拟** **动画模拟**
@ -42,7 +42,6 @@ Java Code:
```java ```java
public class Solution { public class Solution {
public boolean hasCycle(ListNode head) { public boolean hasCycle(ListNode head) {
ListNode fast = head; ListNode fast = head;
ListNode low = head; ListNode low = head;
while (fast != null && fast.next != null) { while (fast != null && fast.next != null) {
@ -80,11 +79,11 @@ class Solution {
public: public:
bool hasCycle(ListNode *head) { bool hasCycle(ListNode *head) {
ListNode * fast = head; ListNode * fast = head;
ListNode * low = head; ListNode * slow = head;
while (fast != nullptr && fast->next != nullptr) { while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next; fast = fast->next->next;
low = low->next; slow = slow->next;
if (fast == low) { if (fast == slow) {
return true; 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
```