# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defhasCycle(self, head: ListNode)->bool:ifnot head ornot head.next:returnFalse
fast = low = head
while fast:
fast = fast.nextif fast:
fast=fast.next
low = low.nextif fast == low:returnTruereturnFalse
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/publicclassSolution{publicboolHasCycle(ListNode head){if(head==null|| head.next==null)returnfalse;ListNode slow = head;ListNode fast = head;while(fast!=null){
fast = fast.next;if(fast!=null) fast = fast.next;if(slow==fast)returntrue;
slow = slow.next;}returnfalse;}}
Java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/publicclassSolution{publicbooleanhasCycle(ListNode head){if(head==null|| head.next==null)returnfalse;ListNode slow = head;ListNode fast = head;while(fast!=null){
fast = fast.next;if(fast!=null) fast = fast.next;if(slow==fast)returntrue;
slow = slow.next;}returnfalse;}}