使用快慢指针,如果存在闭环的话,快慢指针一定会相遇。
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)return true;
}
return false;
}
}
使用Set集合,将所有节点存储到set中,如果后面遍历Set集合中有重复的head那就说明存在环。
import java.util.*;
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
Set<ListNode> set=new HashSet<>();
while(head.next!=null){
if(set.contains(head)){
return true;
}
set.add(head);
head=head.next;
}
return false;
}
}