# @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: ListNode) -> bool: fast=head slow=head while fast and fast.next: fast=fast.next.next slow=slow.next if fast==slow: returnTrue returnFalse
# @lc code=end
cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: boolhasCycle(ListNode *head){ if (!head || !head->next) returnfalse;
ListNode* slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (fast == slow) returntrue; } returnfalse; } };