题目描述
解法:弗洛伊德的龟和兔子
C++ 实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *tortoise = head;
ListNode *hare = head;
while(hare!=NULL && hare->next!=NULL)
{
tortoise = tortoise->next;
hare = hare->next->next;
if(tortoise==hare) return true;
}
return false;
}
};
Python 实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head;
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: return True
return False