Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:维护两个指针,一快一慢,判断两个指针能否相遇。

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2021-05-18
  • 2021-04-23
  • 2021-09-02
猜你喜欢
  • 2021-09-27
  • 2021-12-28
  • 2022-01-31
  • 2021-11-14
  • 2021-10-23
  • 2021-11-13
  • 2021-07-16
  • 2021-11-22
相关资源
相似解决方案