环形链表
题目如下
代码如下
public class Solution
{
public bool HasCycle(ListNode head)
{
if(head==null||head.next==null)
{
return false;
}
ListNode first=head;
ListNode last=head.next;
while(last!=first)
{
if(last==null||last.next==null)
{
return false;
}
first=first.next;
last=last.next.next;
}
return true;
}}
##解题思路
设置一个快指针,一个慢指针,如果快慢指针同时指向一个位置,则说明有环。