-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path141_linked_list_cycle
More file actions
67 lines (58 loc) · 1.55 KB
/
141_linked_list_cycle
File metadata and controls
67 lines (58 loc) · 1.55 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# hash table
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
node_seen = []
curr = head
while curr != None:
if curr in node_seen:
return True
else:
node_seen.append(curr)
curr = curr.next
return False
# two pointers
# 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
"""
if head == None or head.next == None:
return False
fast = head.next
slow = head
while fast != slow:
if fast == None or fast.next == None:
return False
else:
fast = fast.next.next
slow = slow.next
return True
# 2 pointers
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
else:
return None
while head != slow:
slow = slow.next
head = head.next
return head