题目链接

/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
// 时间复杂度O(1), 空间复杂度O(N),s随着链表的变长而变长
public boolean hasCycle2(ListNode head) {
Set<ListNode> set = new HashSet<>();
while(head != null) {
if(!set.add(head)) { // 添加不进去说明有环。
return true;
}
head = head.next;
}
return false;
}
// 我写的快慢指针。
public boolean hasCycle(ListNode head) {
if(head == null) return false;
// 使用双指针
ListNode low = head;
ListNode high = head;
while(high.next != null && high.next.next != null) {
low = low.next;
high = high.next.next;
if(low == high) return true;
}
return false;
}
// 老师的快慢指针
public boolean hasCycle3(ListNode head) {
if(head == null) {
return false;
}
ListNode slow = head;
ListNode quick = head.next; // head已经进行处理,不会为空了
while(slow != quick) {
if(quick == null || quick.next == null) return false;
slow = slow.next;
quick = quick.next.next; // quick.next在前面已经处理了,不会为null
}
return true;
}
}