Skip to content

Commit 3df06e5

Browse files
committed
add 141
1 parent fb7c0a1 commit 3df06e5

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
| 136 | [只出现一次的数字](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第136号问题:只出现一次的数字.md) |
4747
| 138 | [复制带随机指针](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第138号问题:复制带随机指针.md) |
4848
| 139 | [单词拆分](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第139号问题:单词拆分.md) |
49+
| 141 | [环形链表](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第141号问题:环形链表.md) |
4950
| 144 | [二叉树的前序遍历](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第144号问题:二叉树的前序遍历.md) |
5051
| 145 | [二叉树的后序遍历](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第145号问题:二叉树的后序遍历.md) |
5152
| 146 | [LRU缓存机制](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第146号问题:LRU缓存机制.md) |
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# 使用快慢指针求解「环形链表」so easy!
2+
3+
> 本文首发于公众号「五分钟学算法」,是[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。
4+
>
5+
> 个人网站:[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com)
6+
7+
今天分享的题目来源于 LeetCode 上第 141 号问题:环形链表。题目难度为 Easy,目前通过率为 40.4% 。
8+
9+
使用快慢指针的方式去求解 **so easy**
10+
11+
### 题目描述
12+
13+
给定一个链表,判断链表中是否有环。
14+
15+
为了表示给定链表中的环,我们使用整数 `pos` 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 `pos``-1`,则在该链表中没有环。
16+
17+
**示例 1:**
18+
19+
```
20+
输入:head = [3,2,0,-4], pos = 1
21+
输出:true
22+
解释:链表中有一个环,其尾部连接到第二个节点。
23+
```
24+
25+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png)
26+
27+
**示例 2:**
28+
29+
```
30+
输入:head = [1,2], pos = 0
31+
输出:true
32+
解释:链表中有一个环,其尾部连接到第一个节点。
33+
```
34+
35+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png)
36+
37+
**示例 3:**
38+
39+
```
40+
输入:head = [1], pos = -1
41+
输出:false
42+
解释:链表中没有环。
43+
```
44+
45+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png)
46+
47+
**进阶:**
48+
49+
你能用 O(1)(即,常量)内存解决此问题吗?
50+
51+
### 题目解析
52+
53+
这道题是快慢指针的**经典应用**
54+
55+
设置两个指针,一个每次走一步的**慢指针**和一个每次走两步的**快指针**
56+
57+
* 如果不含有环,跑得快的那个指针最终会遇到 null,说明链表不含环
58+
* 如果含有环,快指针会超慢指针一圈,和慢指针相遇,说明链表含有环。
59+
60+
### 动画描述
61+
62+
![](https://raw.githubusercontent.com/MisterBooo/myBlogPic/master/20190627145511.gif)
63+
64+
### 代码实现
65+
66+
```java
67+
//author:程序员小吴
68+
public class Solution {
69+
public boolean hasCycle(ListNode head) {
70+
ListNode slow = head, fast = head;
71+
while (fast != null && fast.next != null) {
72+
slow = slow.next;
73+
fast = fast.next.next;
74+
if (slow == fast) return true;
75+
}
76+
return false;
77+
}
78+
}
79+
```
80+

0 commit comments

Comments
 (0)