-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem142.py
More file actions
37 lines (33 loc) · 857 Bytes
/
problem142.py
File metadata and controls
37 lines (33 loc) · 857 Bytes
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
'''
142. Linked List Cycle II
Solution:
Use a dictionary(hashmap) to store every node that appears. Once find a node that
appeared before, return the node.
'''
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
visited = {}
p = head
while(p):
if visited.get(p) != None:
return p
else:
visited[p] = True
p = p.next
return None
if __name__ == '__main__':
s = Solution()
head = ListNode(3)
head.next = ListNode(2)
head.next.next = ListNode(0)
head.next.next.next = ListNode(-4)
head.next.next.next.next = head.next
print s.detectCycle(head)