题目

图片.png

题解

1. 哈希表

  1. class Solution {
  2. public:
  3. bool hasCycle(ListNode *head) {
  4. unordered_set<ListNode*> seen;
  5. while (head != nullptr) {
  6. if (seen.count(head)) {
  7. return true;
  8. }
  9. seen.insert(head);
  10. head = head->next;
  11. }
  12. return false;
  13. }
  14. };

2.Floyd 判圈算法

图片.png

  1. class Solution {
  2. public:
  3. bool hasCycle(ListNode *head) {
  4. if (head == nullptr || head->next == nullptr) {
  5. return false;
  6. }
  7. ListNode * fast = head->next;
  8. ListNode * slow = head;
  9. while (slow != fast) {
  10. if (fast == nullptr || fast->next == nullptr)return false;
  11. slow = slow->next;
  12. fast = fast->next->next;
  13. }
  14. return true;
  15. }
  16. };