has_cycle.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from typing import Optional
  2. import pytest
  3. from utils import ListNode, arr_to_linklist
  4. def hasCycle(head: Optional[ListNode]) -> bool:
  5. # if not head or not head.next:
  6. # return False
  7. # p = q = head
  8. # while p.next or q.next:
  9. # if q.next is None:
  10. # p = p.next
  11. # q = p.next
  12. # elif p.next is None:
  13. # return False
  14. # elif q.next != p:
  15. # q = q.next
  16. # else:
  17. # return True
  18. # 哈希表法
  19. # res = set()
  20. # while head:
  21. # if head in res:
  22. # return True
  23. # res.add(head)
  24. # head = head.next
  25. # return False
  26. # 快慢指针法
  27. if not head or not head.next:
  28. return False
  29. slow = head
  30. fast = head.next
  31. while fast != slow:
  32. if not fast or not fast.next:
  33. return False
  34. slow = slow.next
  35. fast = fast.next.next
  36. return True
  37. @pytest.mark.parametrize(
  38. "head, expect",
  39. [
  40. ([3,2,0,-4], True)
  41. ]
  42. )
  43. def test_cases(head, expect):
  44. assert hasCycle(arr_to_linklist(head)) == expect