public class 链表中是否有环
{
class ListNode
{
ListNode next;
int val;
ListNode(int x)
{
this.val = x;
this.next = null;
}
}
public boolean hasCycle(ListNode head)
{
if (head == null)
{
return false;
}
// 利用长短步,快的指针两个结点,慢的指针一步一个结点,当快的指针遇见null结束 则链表中没有环,若快的指针遇到慢的指针则,链表中有环
ListNode quick = head;
ListNode slow = head;
while (quick.next != null && quick.next.next != null)
{
quick = quick.next.next;
slow = slow.next;
if (quick == slow)
{
return true;
}
}
return false;
}
}