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

96 lines
3.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
####
> pos-1
>
> true false
1
![](https://img-blog.csdnimg.cn/20210321131949755.png)
> head = [3,2,0,-4], pos = 1
> true
>
####
![](https://img-blog.csdnimg.cn/20210321132015849.png)
\
****
![](https://img-blog.csdnimg.cn/20210321115836276.gif)
****
Java Code:
```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;
}
}
```
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;
};
```
C++ Code:
```cpp
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode * fast = head;
ListNode * low = head;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
low = low->next;
if (fast == low) {
return true;
}
}
return false;
}
};
```