-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path141_Linked_List_Cycle.py
51 lines (46 loc) · 1.2 KB
/
141_Linked_List_Cycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
# def hasCycle(self, head):
# """
# :type head: ListNode
# :rtype: bool
# """
# # Add max and check if reach max
# if head is None:
# return False
# count = 0
# max = 100000
# pos = head
# while pos is not None:
# count += 1
# pos = pos.next
# if count > max:
# return True
# return False
# def hasCycle(self, head):
# # Hash or set
# dic = {}
# pos = head
# while pos is not None:
# try:
# dic[pos]
# return True
# except KeyError:
# dic[pos] = pos
# pos = pos.next
# return False
def hasCycle(self, head):
# Two points
try:
fast = head.next.next
slow = head.next
while fast != slow:
fast = fast.next.next
slow = slow.next
return True
except:
return False