141. 环形链表
原始题目链接:https://leetcode-cn.com/problems/linked-list-cycle/
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
解题思路:
比较直接的方法是,判断链表中是否存在重复的元素,那把遍历到的元素存储在一个集合中,判断集合中是否已经访问过该元素,访问过表示有环。另一个方法是设置快慢指针,一个走一步,一个走两步,不同起点(是为了使用while循环,while循环是先判断条件再执行循环体,如果使用do while循环,可以同一起点,因为do while循环先执行循环体),类似龟兔赛跑,具体实现看代码及注释。
代码实现:
哈希法
# 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:
# 哈希法
nodes = set()
while head:
# 判断当前遍历的节点是否存在哈希表里
if head in nodes:
return True
nodes.add(head)
head = head.next
return False
快慢指针法
# 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:
# 判断至少存在2个节点,否则成不了环
if head is None or head.next is None:
return False
# 设置快慢指针
fast = head.next
slow = head
# 循环条件是slow 不等于 fast
# 等于的话就表示快指针已经追上了慢指针,即存在环,返回True即可
while slow != fast:
# 如果快指针已经达到了链表的尾部,则表示不存在环
if fast is None or fast.next is None:
return False
# 快慢指针前移
fast = fast.next.next
slow = slow.next
# 如果走到这一步,表示while循环体条件不满足,跳出循环,slow=fast
# 存在环
return True
参考文献:
https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/