输入:链表
输出:判定链表内部是否有环
思路:用快慢双指针遍历链表,如果有链表二者一定会相遇;如果没有环,fast会先到nullptr。
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return false;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next; // Move slow pointer by one.
fast = fast->next->next; // Move fast pointer by two.
if (slow == fast) {
return true;
}
}
return false;
}
};
459

被折叠的 条评论
为什么被折叠?



