File tree Expand file tree Collapse file tree 3 files changed +59
-3
lines changed Expand file tree Collapse file tree 3 files changed +59
-3
lines changed Original file line number Diff line number Diff line change 102
102
* [ 98. Validate Binary Search Tree] ( leetCode-98-Validate-Binary-Search-Tree.md )
103
103
* [ 99. Recover Binary Search Tree] ( leetcode-99-Recover-Binary-Search-Tree.md )
104
104
* [ 100. Same Tree] ( leetcode-100-Same-Tree.md )
105
- * [ 101 题到 140题 ] ( leetcode-101-200.md )
105
+ * [ 101 题到 141题 ] ( leetcode-101-200.md )
106
106
* [ 101. Symmetric Tree] ( leetcode-101-Symmetric-Tree.md )
107
107
* [ 102. Binary Tree Level Order Traversal] ( leetcode-102-Binary-Tree-Level-Order-Traversal.md )
108
108
* [ 103. Binary Tree Zigzag Level Order Traversal] ( leetcode-103-Binary-Tree-Zigzag-Level-Order-Traversal.md )
142
142
* [ 137* . Single Number II] ( leetcode-137-Single-NumberII.md )
143
143
* [ 138. Copy List with Random Pointer] ( leetcode-138-Copy-List-with-Random-Pointer.md )
144
144
* [ 139. Word Break] ( leetcode-139-Word-Break.md )
145
- * [ 140. Word Break II] ( leetcode-140-Word-BreakII.md )
145
+ * [ 140. Word Break II] ( leetcode-140-Word-BreakII.md )
146
+ * [ 141. Linked List Cycle] ( leetcode-141-Linked-List-Cycle.md )
Original file line number Diff line number Diff line change 76
76
77
77
<a href =" leetcode-139-Word-Break.html " >139. Word Break</a >
78
78
79
- <a href =" leetcode-140-Word-BreakII.html " >140. Word Break II</a >
79
+ <a href =" leetcode-140-Word-BreakII.html " >140. Word Break II</a >
80
+
81
+ <a href =" leetcode-141-Linked-List-Cycle.html " >141. Linked List Cycle</a >
Original file line number Diff line number Diff line change
1
+ # 题目描述(简单难度)
2
+
3
+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/141.png )
4
+
5
+ 判断一个链表是否有环。
6
+
7
+ # 解法一
8
+
9
+ 最直接的方法,遍历链表,并且把遍历过的节点用 ` HashSet ` 存起来,如果遍历过程中又遇到了之前的节点就说明有环。如果到达了 ` null ` 就说明没有环。
10
+
11
+ ``` java
12
+ public boolean hasCycle(ListNode head) {
13
+ HashSet<ListNode > set = new HashSet<> ();
14
+ while (head != null ) {
15
+ set. add(head);
16
+ head = head. next;
17
+ if (set. contains(head)) {
18
+ return true ;
19
+ }
20
+ }
21
+ return false ;
22
+ }
23
+ ```
24
+
25
+ # 解法二
26
+
27
+ 学数据结构课程的时候,应该都用过这个方法,很巧妙,快慢指针。
28
+
29
+ 原理也很好理解,想象一下圆形跑道,两个人跑步,如果一个人跑的快,一个人跑的慢,那么不管两个人从哪个位置出发,跑的过程中两人一定会相遇。
30
+
31
+ 所以这里我们用两个指针 ` fast ` 和 ` slow ` 。` fast ` 每次走两步,` slow ` 每次走一步,如果 ` fast ` 到达了 ` null ` 就说明没有环。如果 ` fast ` 和 ` slow ` 相遇了就说明有环。
32
+
33
+ ``` java
34
+ public boolean hasCycle(ListNode head) {
35
+ ListNode slow = head;
36
+ ListNode fast = head;
37
+ while (fast != null ) {
38
+ if (fast. next == null ) {
39
+ return false ;
40
+ }
41
+ slow = slow. next;
42
+ fast = fast. next. next;
43
+ if (fast == slow) {
44
+ return true ;
45
+ }
46
+ }
47
+ return false ;
48
+ }
49
+ ```
50
+
51
+ # 总
52
+
53
+ 比较简单的一道题了,快慢指针的思想,也比较常用,很巧妙。
You can’t perform that action at this time.
0 commit comments