思路:
快慢指针。。。当有环出现的时候。我们可以想象出现了一个400米的跑道。。那么如果跑的快的人和跑的慢的人一直在里面跑的话,那么迟早会扣圈。。。我这里快的人每次跑2步,慢的人一次跑1步。。但是这个步数不是随便选的,具体怎么选可以看看资料。。
/**
* 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 pre=head;
ListNode tail=head;
while(true)
{
if(pre!=null&&pre.next!=null)
{
pre=pre.next.next;
tail=tail.next;
}
else
{
break;
}
if(pre==tail)
{
return true;
}
}
return false;
}
}
1179

被折叠的 条评论
为什么被折叠?



