题目:
思路:
利用快慢指针,如果二者相遇,则说明是有环的,如果有节点为null,则说明是无环的
代码:
/**
* 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) {
ListNode s=head;
ListNode f=head; //定义快慢指针
while(true){
if(s!=null && f!=null && s.next!=null && f.next!=null){ //排除特例是无环和单个节点的情况
s=s.next;
f=f.next.next;
}else{
return false;
}
if(f==null||f.next==null){
return false; //说明无环
}
if(s==f){
return true;
}
}
}
}