题目
代码(首刷自解)
class Solution {
public:
bool hasCycle(ListNode *head) {
auto fast = head;
auto slow = head;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
代码(8.7 二刷自解)
class Solution {
public:
bool hasCycle(ListNode *head) {
auto fast = head, slow = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};
GO
func hasCycle(head *ListNode) bool {
fast, slow := head, head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if fast == slow {
return true
}
}
return false
}
代码(9.4 三刷自解)
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head || !head->next)
return false;
auto fast = head, slow = head;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};