algorithm-base/animation-simulation/链表篇/leetcode141环形链表.md

111 lines
3.4 KiB
Java
Raw Normal View History

2021-03-21 04:10:31 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
### [141. ](https://leetcode-cn.com/problems/linked-list-cycle/)
####
2021-07-13 13:06:03 +00:00
> pos-1
2021-03-21 04:10:31 +00:00
>
2021-07-15 16:06:52 +00:00
> true false
2021-03-21 04:10:31 +00:00
1
2021-03-21 05:20:43 +00:00
![](https://img-blog.csdnimg.cn/20210321131949755.png)
2021-03-21 04:10:31 +00:00
> head = [3,2,0,-4], pos = 1
> true
>
####
2021-03-21 05:20:43 +00:00
![](https://img-blog.csdnimg.cn/20210321132015849.png)
2021-03-21 04:10:31 +00:00
2021-07-13 13:06:03 +00:00
2021-03-21 04:10:31 +00:00
****
![](https://img-blog.csdnimg.cn/20210321115836276.gif)
****
2021-04-27 10:14:29 +00:00
Java Code:
2021-03-21 04:10:31 +00:00
```java
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode low = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
low = low.next;
if (fast == low) {
return true;
}
}
return false;
}
}
```
2021-04-28 10:28:00 +00:00
C++ Code:
```cpp
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode * fast = head;
2021-07-13 13:06:03 +00:00
ListNode * slow = head;
2021-04-28 10:28:00 +00:00
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
2021-07-13 13:06:03 +00:00
slow = slow->next;
if (fast == slow) {
2021-04-28 10:28:00 +00:00
return true;
}
}
return false;
}
};
```
2021-07-15 16:06:52 +00:00
JS Code:
```javascript
var hasCycle = function(head) {
let fast = head;
let slow = head;
while (fast && fast.next) {
fast = fast.next.next;
slow = slow.next;
if (fast === slow) {
return true;
}
}
return false;
};
```
2021-07-13 13:06:03 +00:00
Python Code:
2021-07-15 16:06:52 +00:00
```python
2021-07-13 13:06:03 +00:00
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
2021-07-15 16:06:52 +00:00
slow = slow.next
if fast == slow:
2021-07-13 13:06:03 +00:00
return True
return False
```