Skip to content

Commit 045b9b7

Browse files
committed
add 141
1 parent 277b530 commit 045b9b7

File tree

3 files changed

+83
-1
lines changed

3 files changed

+83
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
| 206 | [Reverse Linked List][206] |
5151
| 21 | [Merge Two Sorted Lists][021] |
5252
| 234 | [Palindrome Linked List][234] |
53-
53+
| 141 | [Linked List Cycle][141] |
5454

5555
**其他**
5656

@@ -90,3 +90,4 @@
9090
[206]: https://github.com/andavid/leetcode-java/blob/master/note/206/README.md
9191
[021]: https://github.com/andavid/leetcode-java/blob/master/note/021/README.md
9292
[234]: https://github.com/andavid/leetcode-java/blob/master/note/234/README.md
93+
[141]: https://github.com/andavid/leetcode-java/blob/master/note/141/README.md

note/141/README.md

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# [Linked List Cycle][title]
2+
3+
## Description
4+
5+
Given a linked list, determine if it has a cycle in it.
6+
7+
Follow up:
8+
Can you solve it without using extra space?
9+
10+
## 思路
11+
12+
使用快慢两个指针,慢指针每次前进一步,快指针每次前进两步,如果慢指针和快指针相等,说明有环。
13+
14+
15+
## [完整代码][src]
16+
17+
```java
18+
/**
19+
* Definition for singly-linked list.
20+
* class ListNode {
21+
* int val;
22+
* ListNode next;
23+
* ListNode(int x) {
24+
* val = x;
25+
* next = null;
26+
* }
27+
* }
28+
*/
29+
public class Solution {
30+
public boolean hasCycle(ListNode head) {
31+
ListNode slow = head;
32+
ListNode fast = head;
33+
while (fast != null && fast.next != null) {
34+
slow = slow.next;
35+
fast = fast.next.next;
36+
if (slow == fast) {
37+
return true;
38+
}
39+
}
40+
return false;
41+
}
42+
}
43+
```
44+
45+
[title]: https://leetcode.com/problems/linked-list-cycle
46+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_141/Solution.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
3+
public static boolean hasCycle(ListNode head) {
4+
ListNode slow = head;
5+
ListNode fast = head;
6+
while (fast != null && fast.next != null) {
7+
slow = slow.next;
8+
fast = fast.next.next;
9+
if (slow == fast) {
10+
return true;
11+
}
12+
}
13+
return false;
14+
}
15+
16+
public static class ListNode {
17+
int val;
18+
ListNode next;
19+
ListNode(int x) {
20+
val = x;
21+
}
22+
}
23+
24+
public static void main(String[] args) {
25+
ListNode node1 = new ListNode(1);
26+
ListNode node2 = new ListNode(2);
27+
ListNode node3 = new ListNode(3);
28+
node1.next = node2;
29+
node2.next = node3;
30+
node3.next = node1;
31+
32+
System.out.println(hasCycle(node1));
33+
}
34+
35+
}

0 commit comments

Comments
 (0)