题解 | 判断链表中是否有环
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
咨询了豆包,豆包APP帮忙写的代码
*/
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return false;
}
ListNode* slow = head; // 慢指针,每次走一步
ListNode* fast = head->next; // 快指针,每次走两步
while (slow != fast) {
// 如果快指针到达链表末尾,说明没有环
if (fast == nullptr || fast->next == nullptr) {
return false;
}
slow = slow->next; // 慢指针走一步
fast = fast->next->next; // 快指针走两步
}
// 快慢指针相遇,说明有环
return true;
}
};

