题解 | #判断链表中是否有环# -- 【Python3】
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
1. 快慢指针
class Solution:
def hasCycle(self , head ):
if not head:
return False
slow = head;
fast = head;
while fast and fast.next :
slow = slow.next
fast = fast.next.next
if (slow == fast):
return True
return False
2. 使用集合的方式
把所有的node加入到集合中,如果最后遍历出的node已经存在于集合中,则说明有环,反之则无环
class Solution:
def hasCycle(self , head ):
if not head:
return False
setCycle = set()
while head:
if head in setCycle:
return True
setCycle.add(head)
head = head.next
return False