题目描述
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
思想
有四种想法可以采用:
1.使用collection库中的defaultdict函数来使用字典来确定是否有走过的路。
2.使用快慢指针
下面是两种投机取巧的方法
3.设置最大遍历步数,假设如果超过1000步咱们就把他看作是有环的
4.遍历过的每个元素都给修改了,都改成一样的,如果有环的话,回过头就会遍历到相同的元素,这样就判断这个链表是个环
下面就是代码了
代码1
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
from collections import defaultdict
lookup = defaultdict(int)
p = head
while p:
lookup[p] += 1
if lookup[p] > 1:
return True
p = p.next
return False
代码2
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = head.next
slow = head
while fast!=None and slow!=None:
if fast == None:
return False
elif fast.next == None:
return False
elif fast.next.next ==None:
return False
fast = fast.next.next
slow = slow.next
return True
代码3
class Solution(object):
def hasCycle(self, head):
for i in range(10000):
if head is None:
return False
head = head.next
return True
代码4
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'bjfuvth':
return True
else:
head.val = 'bjfuvth'
head = head.next
return False