题目:
1.思路:
- 通过使用两个快慢指针遍历链表,其中快指针一次循环移动两步,慢指针一次循环移动一步。
- 若有环形链表,则循环以快慢指针相等结束,若没有环形指针,则循环以快指针到达尾部结束。
2.代码:
public class Solution {
public bool HasCycle(ListNode head) {
if(head==null||head.next==null)
return false;
ListNode slow=head;
ListNode fast=head.next;
while(fast!=slow)
{
if(fast==null||fast.next==null)
{return false;}
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}