传送门:141. 环形链表
方法一:Hash表法
"""
思路分析:
判断一个单链表是否有环, 可以用 set 存放每一个节点, 这样每次访问后把节点放到这个集合里面.
其实 可以遍历这个单链表, 访问过后, 如果这个节点 不在 set 里面, 把这个节点放入到 set 集合里面.
如果这个节点在 set 里面 , 说明曾经访问过, 所以这个链表有重新走到了这个节点, 因此一定有环.
如果链表都走完了, 把所有的节点都放完了. 还是没有重复的节点, 那说明没有环.
"""
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
mapping = set()
flag = False
p = head
while p:
if p not in mapping:
mapping.add(p)
else:
flag = True
break
p = p.next
return flag
方法二:快慢指针
"""
思路:快慢指针
快指针走两步,慢指针走一步
有环的话,快指针一定会追上慢指针
"""
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# mapping = set()
if head is None or head.next is None:
return False
p = head.next
q = head.next.next
# while (p and (q.next is not None)):
while (q and (q.next is not None)):
if p == q:
return True
p = p.next
q = q.next.next
# if q.next is not None:
# q = q.next.next
# else:
# return False
return False