Skip to content

Commit 3633f5d

Browse files
authored
update
1 parent 415622c commit 3633f5d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

141.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# 解1
2+
class Solution(object):
3+
def hasCycle(self, head):
4+
#定义一个set,然后不断遍历链表
5+
s = set()
6+
while head:
7+
#如果某个节点在set中,说明遍历到重复元素了,也就是有环
8+
if head in s:
9+
return True
10+
s.add(head)
11+
head = head.next
12+
return False
13+
14+
# 解2: 快慢指针
15+
# class Solution(object):
16+
# def hasCycle(self, head):
17+
# """
18+
# :type head: ListNode
19+
# :rtype: bool
20+
# """
21+
# if not (head and head.next):
22+
# return False
23+
# #定义两个指针i和j,i为慢指针,j为快指针
24+
# i,j = head,head.next
25+
# while j and j.next:
26+
# if i==j:
27+
# return True
28+
# # i每次走一步,j每次走两步
29+
# i,j = i.next, j.next.next
30+
# return False
31+
32+
'''
33+
题:
34+
输入:head = [3,2,0,-4], pos = 1
35+
输出:true
36+
解释:链表中有一个环,其尾部连接到第二个节点。
37+
38+
解:
39+
快慢指针
40+
'''

0 commit comments

Comments
 (0)