File tree Expand file tree Collapse file tree 1 file changed +20
-6
lines changed Expand file tree Collapse file tree 1 file changed +20
-6
lines changed Original file line number Diff line number Diff line change 10
10
11
11
#### 题目描述
12
12
13
- > 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环
13
+ > 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环。
14
14
>
15
15
> 如果链表中存在环,则返回 true 。 否则,返回 false 。
16
16
28
28
29
29
![ 在这里插入图片描述] ( https://img-blog.csdnimg.cn/20210321132015849.png )
30
30
31
- 好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。\
31
+ 好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。
32
32
33
33
** 动画模拟**
34
34
@@ -42,7 +42,6 @@ Java Code:
42
42
``` java
43
43
public class Solution {
44
44
public boolean hasCycle (ListNode head ) {
45
-
46
45
ListNode fast = head;
47
46
ListNode low = head;
48
47
while (fast != null && fast. next != null ) {
@@ -80,11 +79,11 @@ class Solution {
80
79
public:
81
80
bool hasCycle(ListNode * head) {
82
81
ListNode * fast = head;
83
- ListNode * low = head;
82
+ ListNode * slow = head;
84
83
while (fast != nullptr && fast->next != nullptr) {
85
84
fast = fast->next->next;
86
- low = low ->next;
87
- if (fast == low ) {
85
+ slow = slow ->next;
86
+ if (fast == slow ) {
88
87
return true;
89
88
}
90
89
}
@@ -93,3 +92,18 @@ public:
93
92
};
94
93
```
95
94
95
+ Python Code:
96
+
97
+ ```py
98
+ class Solution:
99
+ def hasCycle(self, head: ListNode) -> bool:
100
+ fast = head
101
+ slow = head
102
+ while fast and fast.next:
103
+ fast = fast.next.next
104
+ low = low.next
105
+ if fast == low:
106
+ return True
107
+ return False
108
+ ```
109
+
You can’t perform that action at this time.
0 commit comments