题目
- 给定一个链表,判断链表中是否有环。
思路
- 两个指针,一个每次移动一步,另一个每次移动两步,若有环形,则最终会相遇,若没有,则终会为空。
public bool HasCycle1(ListNode head)
{
ListNode temp1 = head;
ListNode temp2 = head;
while (temp1!=null&&temp2!=null)
{
if (temp2.next != null)
{
temp1 = temp1.next;
temp2 = temp2.next.next;
}
else return false;
if (temp1 == temp2)
return true;
}
return false;
}