方法一:利用Hashset的不可重复的特点
思路:
把每次遍历的节点加入到hashset哈希表中,直到不可加入,说明遇到了重复的,直接返回true即可
/**
* 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> node=new HashSet<ListNode>();
while(head!=null){
if(!node.add(head)){
return true;
}
head=head.next;
}
return false;
}
}
方法二:利用龟兔赛跑的思想,定义快慢指针
思路:
1. 定义两个指针之前先判断head和head.next是否为空
2. 定义前后两个节点slow,quick变量分别指向head,head.next
3. 利用slow!=quick 当做while循环终止条件
4. 在循环里首先判断quck和quick.next是否为空,防止遍历下去出现null的现象
5. slow和quick不停往下遍历
/**
* 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) {
while(head==null||head.next==null){
return false;
}
ListNode slow=head;
ListNode quick=head.next;
while(slow!=quick){
if(quick==null||quick.next==null){
return false;
}
slow=slow.next;
quick=quick.next.next;
}
return true;
}
}