本文最后更新于211 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com
1.题目基本信息
1.1.题目描述
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
1.2.题目地址
https://leetcode.cn/problems/linked-list-cycle/description/
2.解题方法
2.1.解题思路
哈希表 / 快慢指针
2.2.解题步骤
快慢指针
-
第一步,构建快慢双指针。fast指向head.next是为了后面的slow!=fast的比较别在第一步就跳出了
-
第二步,移动双指针,更新维护变量;如果是循环链表,则一定会走到slow==fast
3.解题代码
python3代码-哈希表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# 思路:哈希表
recordSet = set()
node = head
recordSet.add(node)
while node is not None:
node=node.next
if node in recordSet:
return True
recordSet.add(node)
return False
python3代码-快慢指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# 思路2:快慢指针
if head is None:
return False
# 第一步,构建快慢双指针。fast指向head.next是为了后面的slow!=fast的比较别在第一步就跳出了
slow, fast = head, head.next
# 第二步,移动双指针,更新维护变量;如果是循环链表,则一定会走到slow==fast
while slow != fast:
if fast is None or fast.next is None:
return False
slow = slow.next
fast = fast.next.next
return True
4.执行结果










