此题一看就是two point的问题,这类问题肯定是一个先走一个后走,要么是按照倍速一快一慢,要么是一个先走多少步,再两者同时走(找公共子链的问题)。
此题就是按照倍速,若有循环则快者必将追上慢者。
代码如下:
/**
* 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 fast=head,slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow)return true;
}
return false;
}
}