leetcode地址:https://leetcode-cn.com/problems/linked-list-cycle/。
java代码:
publicclass_141_环形链表 {
classListNode {
intval;
ListNodenext;
ListNode(intx) {
val=x;
next=null;
}
}
publicbooleanhasCycle(ListNodehead) {
if(head==null||head.next==null)
{
return false;
}
//快慢指针
ListNodeslowListNode = head;
ListNodefastListNode=head.next;
while(fastListNode != null && fastListNode.next != null)
{
if(slowListNode == fastListNode)
{
return true;
}
slowListNode = slowListNode.next;
fastListNode = fastListNode.next.next;
}
return false;
}
}
网友评论