题目描述:
题解一(快慢指针):
参考:【leetcode】Python实现-141.环形链表_神不烦-CSDN博客_python 环形链表
1.创建一个指针slow,一个指针fast。slow每次向后移动一个节点,fast每次向后移动两个节点。
2.如果链表有环,则slow fast必然会相遇。
注意while循环条件为fast!=None and fast.next!=None
class Solution(object): def hasCycle(self, head): if head == None or head.next==None or head.next.next==None: return False slow = head.next fast = head.next.next while fast and fast.next: if slow==fast: return True else: slow = slow.next fast = fast.next.next return False
题解二(列表保存遍历过的节点):
1.创建一个list lp,保存便利过的节点。
2.从head开始遍历链表,如果节点p在lp中,说明存在环,否则将p添加进lp,p=p.next
class Solution(object): def hasCycle(self, head): if head == None or head.next==None: return False p = head lp = [] while p and p.next: if p in lp: return True else: lp.append(p) p = p.next return False