Leetcode # 141. Linked List Cycle

https://leetcode.com/problems/linked-list-cycle/

Solution

Time Complexity: O(len(linked_list))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution {
public:
  bool hasCycle(ListNode *head) {
    ListNode *hare = head, *tortorise = head;
    while(hare != NULL && tortorise != NULL){
      hare = hare->next;
      if(hare != NULL)hare = hare->next;
      tortorise = tortorise->next;
      if(hare == tortorise)break;
    }
    return hare != NULL;
  }
};

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami