/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//时间复杂度:O(n),空间复杂度:O(n)需要把所有的节点都存放在map中
import java.util.*;
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
Map<ListNode,Integer> map = new HashMap<>();
while(head!=null){
if(map.containsKey(head)){
return true;
}
map.put(head,head.val);
head = head.next;
}
return false;
}
}
//使用快慢指针,时间复杂度:O(n),空间复杂度:O(1)
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
ListNode slow = head;
ListNode fast = head;
while(slow!=null&&fast!=null){
slow = slow.next;
if(fast.next!=null){
fast = fast.next.next;
}else{
return false;
}
if(slow==fast)
return true;
}
return false;
}