/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
//双指针判断是否有环
ListNode p1 = head;
ListNode p2 = head;
while(p1 != null && p2 != null && p2.next != null){
p1 = p1.next;
p2 = p2.next.next;
if(p1 != null && p2 != null && p1.val == p2.val){
return true;
}
}
return false;
}
}

京公网安备 11010502036488号