Leetcode刻意练习----链表3
题目
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 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:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
a = []
while head != None:
if head in a:
return True
else:
a.append(head)
head = head.next
return False
看了一些题解之后又找到了以下两种方法
法二
当 head.next 不为空时,将head.next 指向 head.next.next,相当于去掉了next节点,到最后如果有环,head == head.next 。(此种方法破坏了链表)
# 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:
while head != None:
if head == head.next:
return True
if head.next != None:
head.next = head.next.next
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:
if head == None:
return False
a = head
b = head.next
while a != b:
if b == None or b.next == None:
return False
a = a.next
b = b.next.next
return True