import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
//首先判断是否为空
if(head == null) return false;
ListNode fast = head;
ListNode slow = head;
//设置快慢两种指针,快的每次走两步,慢的每次走一步,如果会相遇代表有环
while(fast!= null && fast.next!=null&& fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow) return true;
}
return false;
}
}
时间复杂度O(n),空间复杂度O(1)
看到题解另一种做法是利用哈希表,因为没写过,就当练习一下java____过分简单了
import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while(head!=null && head.next!=null){
if(set.contains(head)) return true;
set.add(head);
head = head.next;
}
return false;
}
}
时间复杂度和空间复杂度都是O(n)