代码实现:
public class HasCycle {
public static void main(String[] args) {
}
//hashMap
public boolean hasCycle1(ListNode head) {
Map<ListNode,Integer> hashMap = new HashMap<>();
int index = 0;
while (head != null){
if (hashMap.containsKey(head)){
return true;
}
hashMap.put(head,index);
index ++;
head = head.next;
}
return false;
}
//特殊值
public boolean hasCycle(ListNode head) {
int value = 1000000;
while (head != null){
if (head.val == value){
return true;
}
head.val = value;
head = head.next;
}
return false;
}
}