//set集合 时间复杂度是O(n)
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
Set<ListNode> listSet = new HashSet<>();
while (head != null) {
if (!listSet.add(head)) {
return true;
}
head = head.next;
}
return false;
}
//快慢指针 时间复杂度是O(n)
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head,fast = head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
环相交的位置:利用set很方便,同上,
还有一种是让当前结点为头结点,则他走的位置和fast或flow相交的位置一定是第一个入环部分
public int hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head,fast = head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
fast = head;
while(fast != slow){
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
return null;
}