核心思路:HashSet/快慢指针
我的方法:
空间复杂度为O(n)
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while(head != null){
if(set.contains(head)){
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
官方题解:
空间复杂度为O(1)
思路:
具体地,定义两个指针,一快一满。慢指针每次只移动一步,而快指针每次移动两步。初始时,慢指针在位置 head,而快指针在位置 head.next。这样一来,如果在移动的过程中,快指针反过来追上慢指针,就说明该链表为环形链表。否则快指针将到达链表尾部,该链表不为环形链表。
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode slow = head;
ListNode quick = head.next;
//while的离开条件只能是慢指针追上快指针(忽略while中的renturn)
while(slow != quick){
//不用考虑慢指针,看快指针就行
if(quick == null || quick.next == null){
return false;
}
//慢指针走一步
slow = slow.next;
//快指针走两步
quick = quick.next.next;
}
return true;
}
}