File tree Expand file tree Collapse file tree 3 files changed +65
-0
lines changed
solution/141.Linked List Cycle Expand file tree Collapse file tree 3 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -31,6 +31,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
31
31
| 070 | [ Climbing Stairs] ( https://github.com/doocs/leetcode/tree/master/solution/070.Climbing%20Stairs ) | ` Dynamic Programming ` |
32
32
| 083 | [ Remove Duplicates from Sorted List] ( https://github.com/doocs/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List ) | ` Linked List ` |
33
33
| 136 | [ Single Number] ( https://github.com/doocs/leetcode/tree/master/solution/136.Single%20Number ) | ` Hash Table ` , ` Bit Manipulation ` |
34
+ | 141 | [ Linked List Cycle] ( https://github.com/doocs/leetcode/tree/master/solution/141.Linked%20List%20Cycle ) | ` Linked List ` , ` Two Pointers ` |
34
35
| 189 | [ Rotate Array] ( https://github.com/doocs/leetcode/tree/master/solution/189.Rotate%20Array ) | ` Array ` |
35
36
| 198 | [ House Robber] ( https://github.com/doocs/leetcode/tree/master/solution/198.House%20Robber ) | ` Dynamic Programming ` |
36
37
| 203 | [ Remove Linked List Elements] ( https://github.com/doocs/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements ) | ` Linked List ` |
Original file line number Diff line number Diff line change
1
+ ## 环形链表
2
+ ### 题目描述
3
+
4
+ 给定一个链表,判断链表中是否有环。
5
+
6
+ ** 进阶:**
7
+ 你能否不使用额外空间解决此题?
8
+
9
+ ### 解法
10
+
11
+ 利用快慢指针,若快指针为 null,则不存在环,若快慢指针相遇,则存在环。
12
+
13
+ ``` java
14
+ /**
15
+ * Definition for singly-linked list.
16
+ * class ListNode {
17
+ * int val;
18
+ * ListNode next;
19
+ * ListNode(int x) {
20
+ * val = x;
21
+ * next = null;
22
+ * }
23
+ * }
24
+ */
25
+ public class Solution {
26
+ public boolean hasCycle (ListNode head ) {
27
+ ListNode slow = head;
28
+ ListNode fast = head;
29
+ while (fast != null && fast. next != null ) {
30
+ slow = slow. next;
31
+ fast = fast. next. next;
32
+ if (slow == fast) {
33
+ return true ;
34
+ }
35
+ }
36
+ return false ;
37
+ }
38
+ }
39
+ ```
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode(int x) {
7
+ * val = x;
8
+ * next = null;
9
+ * }
10
+ * }
11
+ */
12
+ public class Solution {
13
+ public boolean hasCycle (ListNode head ) {
14
+ ListNode slow = head ;
15
+ ListNode fast = head ;
16
+ while (fast != null && fast .next != null ) {
17
+ slow = slow .next ;
18
+ fast = fast .next .next ;
19
+ if (slow == fast ) {
20
+ return true ;
21
+ }
22
+ }
23
+ return false ;
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments