141. Linked List Cycle 环型链表
一、刷题内容
原题链接
https://leetcode-cn.com/problems/linked-list-cycle/
内容描述
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 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
解释:链表中没有环。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
解释:
上面示例中的 pos,是无关我们的变量,告诉我们链尾是指向 第pos个元素的
二、解题方案
1.方法一:字典
通过检查一个结点此前是否被访问过来判断链表是否为环形链表,通常用哈希表,这里用了字典。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
lookup = {}
while head:
if head not in lookup:
lookup[head] = 1 # 字典中可以直接将head作为key,key值为存储的引用
else:
return True
head = head.next
return False
2.方法二:快慢双指针
对于一个环,快指针移动的比慢指针快,总是会追上慢指针,反之无环,快指针终点
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None or head.next == None:
return False
slow = head # 慢指针
fast = head.next # 快指针
while slow != fast:
if fast == None or fast.next == None:
return False
slow = slow.next # 慢指针一次移动一个节点
fast = fast.next.next # 快指针一次移动两个节点
return True
3.方法三:快慢双指针
这个效率比上面的高和简洁
class Solution(object):
def hasCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow: # 快指针追上慢指针,有环返回
return True
return False
4.方法四:暴力破坏链表
一般解法还是快慢指针和哈希表
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head and head.val != None:
head.val, head = None, head.next
return head != None