Skip to content

Commit f464320

Browse files
committed
Add solution 141 [Java]
1 parent efe9250 commit f464320

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
3131
| 070 | [Climbing Stairs](https://github.com/doocs/leetcode/tree/master/solution/070.Climbing%20Stairs) | `Dynamic Programming` |
3232
| 083 | [Remove Duplicates from Sorted List](https://github.com/doocs/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List) | `Linked List` |
3333
| 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` |
3435
| 189 | [Rotate Array](https://github.com/doocs/leetcode/tree/master/solution/189.Rotate%20Array) | `Array` |
3536
| 198 | [House Robber](https://github.com/doocs/leetcode/tree/master/solution/198.House%20Robber) | `Dynamic Programming` |
3637
| 203 | [Remove Linked List Elements](https://github.com/doocs/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

0 commit comments

Comments
 (0)