![]()
解题思路:快慢指针,一个一步一步走,一个两步两步走,如果有环,则一定会相遇;如果没环,那么快的指针一定会找到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) {
if(head==null) return false;
ListNode dummy_head = new ListNode();
dummy_head.next = head;
ListNode fast = dummy_head.next.next;
ListNode slow = dummy_head.next;
while(fast!=slow){
if(fast==null || fast.next==null || fast.next.next==null){
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}