-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode141.java
More file actions
38 lines (34 loc) · 1.16 KB
/
LeetCode141.java
File metadata and controls
38 lines (34 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import util.ListNode;
public class LeetCode141 {
public static void main(String[] args) {
ListNode head;
// 输入:head = [3,2,0,-4], pos = 1
// 输出:true
head = ListNode.buildLinkedList(new Integer[] { 3, 2, 0, -4 });
head.next.next.next.next = head.next;
System.out.println(new Solution141().hasCycle(head));
// 输入:head = [1,2], pos = 0
// 输出:true
head = ListNode.buildLinkedList(new Integer[] { 1, 2 });
head.next.next = head;
System.out.println(new Solution141().hasCycle(head));
// 输入:head = [1], pos = -1
// 输出:false
head = new ListNode(1);
System.out.println(new Solution141().hasCycle(head));
}
}
class Solution141 {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (slow != null && slow.next != null && fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
return true;
}
}
return false;
}
}