题目描述:

image.png

示例:

image.png
image.png
image.png
解题思路:使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。(快慢双指针)

解:

public boolean hasCycle(ListNode head) {

if(head==null){

return false;

}

ListNode l1=head;

ListNode l2=head.next;

while(l2!=null && l2.next!=null){

if(l1==l2){

return true;

}

l1=l1.next;

l2=l2.next.next;

}

return false;

}